<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Borrow_model extends CI_Model {
	
	function __construct(){
        parent::__construct();
    }
    
    //标的参数信息
	function arrays($key){
    	$data = array(
    		'borrow_type' 			=>self::get_borrow_type(),
    		'borrow_status' 		=> array("-1"=>"尚未发布", "0"=>"待发布", "1"=>"借款中", "3"=>"满额成功", 
    				"2"=>"审核未通过", "4"=>"满额未发布", "5"=>"满标审核未通过"),
    	
    		// TODO 新增宝付交易状态
    		'bor_bf_trade_status' 		=> array(
    				"1"=>"宝付:申请满标交易成功"	, 	"5"=>"宝付:申请还款交易成功",
    				"2"=>"宝付:申请满标交易失败"	, 	"6"=>"宝付:申请还款交易失败",
    				"3"=>"宝付:满标交易成功", 		"7"=>"宝付:还款交易成功",
    				"4"=>"宝付:满标交易失败", 		"8"=>"宝付:还款交易失败"),
    		// ------ end
    		'borrow_work_time' => array(2=>"起始计息"),
    		'borrow_account'=> array("1"=>"10万以下","2"=>"10万-20万","3"=>"20-50万","4"=>"50-100万","5"=>"100万以上"),
    		'borrow_apr'=> array("1"=>"12%以下 ","2"=>"12%-20%","3"=>"20%以上"),
    		'borrow_style' 			=> array("1"=>"按月付息，到期还本", "2"=>"按月还款，等额本息",3=>'一次性还款'),
    		'borrow_award' 			=> array("1"=>"利率奖励", ),
    		'borrow_good' 			=> array("1"=>"完整", "2"=>"基本完整",3=>"有残缺"),
    		'borrow_lowest_account' => array("50.00"=>"50元", "100.00"=>"100元", "0.00"=>"无限制"),
			'borrow_most_account' 	=> array("0.00"=>"无限制", "1000.00"=>"1000元", "10000.00"=>"10000元", "18000.00"=>"18000元"),
			'borrow_valid_time' 	=> array("1"=>"1天", "2"=>"2天", "3"=>"3天", "4"=>"4天", "5"=>"5天", "6"=>"6天", "7"=>"7天"),
    		'borrow_time_limit_query' 	=> array("1"=>"1个月以下", "2"=>"1~3个月", "3"=>"3~6个月", "4"=>"6~12个月",  "5"=>"12个月以上", ),
    		'borrow_time_limit' 	=> array("0"=>"0个月", "1"=>"1个月", "2"=>"2个月", "3"=>"3个月", "6"=>"6个月", "9"=>"9个月", "10"=>"10个月", "12"=>"12个月", "18"=>"18个月", "24"=>"24个月", "36"=>"36个月"),
    		'borrow_day_time_limit' => array(
"1"  =>"1"  ,"2"  =>"2"  ,"3"  =>"3"  ,"4"  =>"4"  ,"5"  =>"5"  ,"6"  =>"6"  ,"7"  =>"7"  ,"8"  =>"8"  ,"9"  =>"9"  ,"10" =>"10" ,
"11" =>"11" ,"12" =>"12" ,"13" =>"13" ,"14" =>"14" ,"15" =>"15" ,"16" =>"16" ,"17" =>"17" ,"18" =>"18" ,"19" =>"19" ,"20" =>"20" ,
"21" =>"21" ,"22" =>"22" ,"23" =>"23" ,"24" =>"24" ,"25" =>"25" ,"26" =>"26" ,"27" =>"27" ,"28" =>"28" ,"29" =>"29" ,"30" =>"30" ,
"31" =>"31" ,"32" =>"32" ,"33" =>"33" ,"34" =>"34" ,"35" =>"35" ,"36" =>"36" ,"37" =>"37" ,"38" =>"38" ,"39" =>"39" ,"40" =>"40" ,
"41" =>"41" ,"42" =>"42" ,"43" =>"43" ,"44" =>"44" ,"45" =>"45" ,"46" =>"46" ,"47" =>"47" ,"48" =>"48" ,"49" =>"49" ,"50" =>"50" ,
"51" =>"51" ,"52" =>"52" ,"53" =>"53" ,"54" =>"54" ,"55" =>"55" ,"56" =>"56" ,"57" =>"57" ,"58" =>"58" ,"59" =>"59" ,"60" =>"60" ,
"61" =>"61" ,"62" =>"62" ,"63" =>"63" ,"64" =>"64" ,"65" =>"65" ,"66" =>"66" ,"67" =>"67" ,"68" =>"68" ,"69" =>"69" ,"70" =>"70" ,
"71" =>"71" ,"72" =>"72" ,"73" =>"73" ,"74" =>"74" ,"75" =>"75" ,"76" =>"76" ,"77" =>"77" ,"78" =>"78" ,"79" =>"79" ,"80" =>"80",
"81" =>"81" ,"82" =>"82" ,"83" =>"83" ,"84" =>"84" ,"85" =>"85" ,"86" =>"86" ,"87" =>"87" ,"88" =>"88" ,"89" =>"89" ,"90" =>"90" ,
"91" =>"91" ,"92" =>"92" ,"93" =>"93" ,"94" =>"94" ,"95" =>"95" ,"96" =>"96" ,"97" =>"97" , "98" =>"98" , "99" =>"99" , "100"=>"100",  
"101"=>"101",  "102"=>"102",  "103"=>"103","104"=>"104","105"=>"105","106"=>"106","107"=>"107","108"=>"108","109"=>"109","110"=>"110",
"111"=>"111","112"=>"112","113"=>"113","114"=>"114","115"=>"115","116"=>"116","117"=>"117","118"=>"118","119"=>"119","120"=>"120",
"121"=>"121","122"=>"122","123"=>"123","124"=>"124","125"=>"125","126"=>"126","127"=>"127","128"=>"128","129"=>"129","130"=>"130",
"131"=>"131","132"=>"132","133"=>"133","134"=>"134","135"=>"135","136"=>"136","137"=>"137","138"=>"138","139"=>"139","140"=>"140",
"141"=>"141","142"=>"142","143"=>"143","144"=>"144","145"=>"145","146"=>"146","147"=>"147","148"=>"148","149"=>"149","150"=>"150",
"151"=>"151","152"=>"152","153"=>"153","154"=>"154","155"=>"155","156"=>"156","157"=>"157","158"=>"158","159"=>"159","160"=>"160",
"161"=>"161","162"=>"162","163"=>"163","164"=>"164","165"=>"165","166"=>"166","167"=>"167","168"=>"168","169"=>"169","170"=>"170",
"171"=>"171","172"=>"172","173"=>"173","174"=>"174","175"=>"175","176"=>"176","177"=>"177","178"=>"178","179"=>"179","180"=>"180",
    										 
    		),
	    	'borrow_fast_sex'		=> array("0"=>"男","1"=>"女"),
    		'user_self' 	=> array("0"=>"客户", "1"=>"马甲"),	
    		'borrow_tender_status' 	=> array("0"=>"待审核", "1"=>"成功","2"=>"失败", "3"=>"宝付处理中"),

    		// TODO 新增宝付投标交易、还款状态
    		'bor_tend_bf_status' 		=> array(
    			"1"=>"宝付:申请投标成功"	, 
    			"2"=>"宝付:申请投标失败"	,
    			"3"=>"宝付:投标成功", 		
    			"4"=>"宝付:投标失败"), 	
    	
    	    'bor_repay_bf_status' 		=> array(
    			"1"=>"宝付:申请还款成功",
    			"2"=>"宝付:申请还款失败",
    			"3"=>"宝付:还款成功",
    			"4"=>"宝付:还款失败"),
    		// ------ end
    	
    		'borrow_verify' =>array(0=>"未初检",1=>"初检通过",2=>"初检失败"),
    		'borrow_check' =>array(0=>"未复检",1=>"复检通过",2=>"复检失败"),
    		'borrow_fuse' =>self::get_borrow_fuse(),							
    	);
    	if($key == 'borrow_bill_bank'){
	    	$bank = 'borrow_bill_bank';
			//$row = $this->mycache->get_array($bank);
			//if($row == false){
				$sql = "select id,name from rsh_linkage where type_id= 25 ";
				$query = $this->db->query($sql);;
				$res = $query->result_array ();
				foreach($res as $val){
					$row [$val['id']] =  $val['name'];
				}
				//$this->mycache->set_array($bank,$row);
			//}
			return $row;
    	}
    	if($key && isset($data[$key])){
    		return $data[$key];
    	}else{
    		return array();
    	}
    }
    
	/**
	 * 发标
	 * @param $data
	 */
	function add($data = array()){
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
   	 	$this->db->trans_begin();
		
		$this->db->insert('rsh_borrow', $data);
		
		$borrow_id = $this->db->insert_id();
		if ($this->db->trans_status() === TRUE) {
       	 	$this->db->trans_commit();
        	return 1;
	    } else {
	        $this->db->trans_rollback();
	        //@todo 异常处理部分
	        return 0;
	    }
	}
	
	// by liub 20140101 获取资金用途
	private  function get_borrow_fuse (){
    	$this->load->model('Conset_model');
		$row = $this->Conset_model->get_use_title_list();
    	return $row;
	}
	
	// by liub 20150408 获取标的类型
	public  function get_borrow_type ($type,$where){
    		$this->db->select(' * ');
    		if(isset($where) && count($where)>0) $this->db->where($where);
			$query = $this->db->get('rsh_borrow_type');		
			$result = $query->result_array();
			$list = array();
			if(!isset($type)){
				if($result){
				foreach ( $result as $v ) {
						$list[$v['id']] = $v['name'];
					}
				}
			}
			else $list = $result;
		return $list;
	}
	
	public function update_borrow_type($data,$where){
		if(isset($where) && count($where)>0) $this->db->where($where);
		$query = $this->db->update('rsh_borrow_type',$data);
		return $query;
	}
	
	/**
	 * 审标
	 * @param int $id 标id
	 * @param array $data
	 * @return number
	 */
	function verify($id, $data = array()){
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
		$fstatus = $data['fstatus'];
		$borrow = $this->Borrow_model->get_borrow_obj($id);
				
		self::update($id, $data);
				
		if ($this->db->trans_status() === TRUE) {
	        $this->db->trans_commit();
	        return 1;
	    } else {
	        $this->db->trans_rollback();
	        //@todo 异常处理部分
	        return 0;
	    }
	}
	
	/**
	 * 发标
	 * @param $data
	 */
	function add_fast($data = array()){
		$this->db->insert('rsh_borrow_fast', $data);
		return $this->db->insert_id();
	}
	
	/**
	 * 添加自动投标信息
	 * @param array $data
	 */
	function add_borrow_auto($data = array()){
		$this->db->insert('rsh_borrow_auto', $data);
		$key = 'auto_tender_count';
		$this->mycache->delete($key);
		return $this->db->insert_id();
	}
	
	/**
	 * 是否有重合日期的自动投标信息
	 * @param array $data
	 */
	function is_date_borrow_auto($data = array()){
		$where = " is_del=0 and user_id='".$data['user_id']."' and (".$data['valid_end_time'].">valid_start_time and valid_end_time>".$data['valid_start_time']." )";
		if(isset($data['id']) && $data['id'] !='') $where = " id!='". $data['id']."' and ".$where;
		$select = " count(1) as cou ";
		$sql = "select ".$select." from rsh_borrow_auto where ".$where;
		$query = $this->db->query($sql);
		$query = $query->row_array();;
		if($query['cou'] > 0) return false;
		else return true;
	}
	
	/**
	 * 是否有重合日期的自动投标信息
	 * @param array $data
	 */
	function count_borrow_auto($data = array()){
		$where = " is_del=0 and user_id='".$data['user_id']."'";
		$select = " count(1) as cou ";
		$sql = "select ".$select." from rsh_borrow_auto where ".$where;
		$query = $this->db->query($sql);
		$query = $query->row_array();
		return $query['cou'];
	}
	
	
	/**
	 * 修改标信息
	 * @param $data
	 */
	function update($id, $data){
		$this->db->where('id', $id);
		$this->db->update('borrow', $data);
		return $this->db->affected_rows();
	}
	
	function update_hits($id){
		//$this->db->query("update rsh_borrow set hits=hits+1 where id={$id}");
	}
	

	/**
	 * 修改标信息
	 * @param $data
	 */
	function update_fast($id, $data){
		$this->db->where('id', $id);
		$this->db->update('rsh_borrow_fast', $data);
		return $this->db->affected_rows();
	}

	/**
	 * 删除标
	 * @param $data
	 */
	function delete($data = array()){
		$this->db->where('id', $data['id']);
		$this->db->update('rsh_borrow', array('is_del'=>1));
	}
	

	/**
	 * 查询
	 * @param $data
	 */
	function get_borrow_obj($id, $data = array()){
		$select = "*";
		$this->db->select($select);
		$this->db->where('id', $id);//防止SQL注入
		$query = $this->db->get('rsh_borrow');
		return $query->row_array();
	}
	
	
	function get_borrow_tender_obj($id, $data = array()){
		$select = "*";
		if(isset($data['select']) && $data['select'] == 1){
			$select = "id,user_id,fstatus,borrow_id,money,account,repayment_account,interest,
						repayment_yesaccount,repayment_yesinterest,wait_account,wait_interest,add_time ";
		}
		$this->db->select($select);
		$this->db->where('id', $id);
		$query = $this->db->get('rsh_borrow_tender');
		return $query->row_array();
	}
	
	function get_borrow_tender_list($data = array()){
		$select = "*";
		if(isset($data['select']) && $data['select'] == 1){
			$select = " t1.id,t1.user_id,t1.fstatus,t1.borrow_id,t1.money,t1.account,t1.repayment_account,t1.interest,
						t1.repayment_yesaccount,t1.repayment_yesinterest,t1.wait_account,t1.wait_interest,t1.add_time,
						t2.title
						";
		}
		
		//封装条件
		$_where = " where 1=1 ";
		if(isset($data['where']['borrow_id']) && $data['where']['borrow_id'] >0){
			$_where .= " and t1.borrow_id = ".$data['where']['borrow_id'];
		}
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] != ''){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['user_id']) && $data['where']['user_id'] > 0){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		
		//排序
		$_order  = " order by t1.id desc ";
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_tender as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$sql_result .= " limit $page_start, $page_size";
		
		$query = $this->db->query($sql_result);
		$borrow_tender_list = $query->result_array();
		if(count($borrow_tender_list) < 1){
			return array();
		}
		return $borrow_tender_list;
	}
	
	function index_borrow_tender_list($data = array()){
		$mkey = "index_borrow_tender_list";
		//$this->mycache->delete($mkey);
		$ret = $this->mycache->get_array($mkey);
		if($ret != false){
			return $ret;
		}
		
		$select = "t1.id,t1.borrow_id,t1.user_id,t2.username,t1.account,t1.add_time,t3.title";
		
		//封装条件
		$_where = " where t1.account>0 ";
		
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		
		//排序
		$_order  = " order by t1.id desc ";
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$sql_result .= " limit $page_start, $page_size";
		
		$query = $this->db->query($sql_result);
		$borrow_tender_list = $query->result_array();
		if(count($borrow_tender_list) < 1){
			return array();
		}
		$this->mycache->set_array($mkey,$borrow_tender_list, 180);
		return $borrow_tender_list;
	}
	

	function borrow_tender_user_list($data = array()){
			$select = "t1.fstatus as tender_fstatus,t1.id,t1.borrow_id,t1.money,t1.wait_interest,
			t1.repayment_account,t1.repayment_yesinterest,t1.interest,t1.user_id,
			t1.account,t1.add_time,t2.username,t2.realname,t2.phone,t2.card_id,t3.user_id borr_user_id,t3.title,t3.account borr_acc,t3.fuse,t3.apr,
			t3.fstatus,t3.is_day,t3.time_limit_day,t3.time_limit,t3.bill_bank,
			t3.account_yes,t3.repayment_account,t3.repayment_yesaccount,t3.bill_starttime,t3.ftype";
		
		
		//封装条件
		$_where = " where 1=1 ";
		
		if (isset($data['where']['ten_id']) && $data['where']['ten_id'] != ''){
			$_where .= " and t1.id = ".$data['where']['ten_id'];
		}
		
		if (isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		if(isset($data['where']['username']) && $data['where']['username'] != ''){
			$_where .= " and t2.username = '".trim($data['where']['username'])."'";
		}
		
		if(isset($data['where']['is_self']) && $data['where']['is_self'] != -1){
			$_where .= " and t2.is_self=".$data['where']['is_self'];
		}
		
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] != -1){
			$_where .= " and t1.fstatus in (".$data['where']['fstatus'].")";
		}
		
		if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
			$strtime = strtotime($data['where']['strtime'].' 00:00:00');
			$_where .= " and t1.add_time >= ".$strtime;
		}
		if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
			$endtime = strtotime($data['where']['endtime'].' 23:59:59');
			$_where .= " and t1.add_time <= ".$endtime;
		}
		
		if(isset($data['where']['title']) && $data['where']['title'] != ''){
			$_where .= " and t3.title = '".$data['where']['title']."'";
		}
		
		if(isset($data['where']['time_limit']) && $data['where']['time_limit'] != -1){
			$_where .= " and t3.time_limit = ".$data['where']['time_limit'];
		}
		
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		//排序
		$_order  = " order by t1.id desc ";
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_result .= $_where;
		$sql_result .= $_order;
		if(isset($data['limit']) && $data['limit'] == 'all'){
			$query = $this->db->query($sql_result);
			$data['tender_list'] = $query->result_array();
			return $data;
		}else{
			$sql_result .= " limit $page_start, $page_size";
			$query = $this->db->query($sql_result);
			$data['tender_list'] = $query->result_array();
		}	
		//echo $sql_result;exit;
		
		//总记录条数
		$sql_count = "select count(1) as count from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['tender_count'] = $query->row()->count;
		
		//投资总人数
		$sql_user_count = "select count(DISTINCT(t2.user_id)) as count from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_user_count .= $_where;
		$query = $this->db->query($sql_user_count);
		$data['tender_user_count'] = $query->row()->count;
		
		//投资金额
		$sql_money_sum = "select sum(t1.account) as count from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_money_sum .= $_where;
		
		$query = $this->db->query($sql_money_sum);
		$data['tender_money_count'] = $query->row()->count;
		
		return $data;
	}
	
	//********** 21041130 by liub 
	function borrow_tender_user_list_01($data = array()){
		$select = "t1.id,t1.borrow_id,t1.repayment_account,t1.interest,t1.user_id,t1.fstatus,t2.username,t1.account,t1.add_time,t3.title,t3.ftype,t3.apr,t3.time_limit,t3.is_day,t3.time_limit_day";
		
		//封装条件
		$_where = " where 1=1 ";
		
		if (isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		if(isset($data['where']['username']) && $data['where']['username'] != ''){
			$_where .= " and t2.username = '".trim($data['where']['username'])."'";
		}
		
		if(isset($data['where']['is_self']) && $data['where']['is_self'] != -1){
			$_where .= " and t2.is_self=".$data['where']['is_self'];
		}
		
		//****** by liub 
		$_where .= " and (t1.fstatus= 0 or t1.fstatus= 1)";
		
		if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
			$strtime = strtotime($data['where']['strtime'].' 00:00:00');
			$_where .= " and t1.add_time >= ".$strtime;
		}
		if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
			$endtime = strtotime($data['where']['endtime'].' 23:59:59');
			$_where .= " and t1.add_time <= ".$endtime;
		}
		
		if(isset($data['where']['title']) && $data['where']['title'] != ''){
			$_where .= " and t3.title = '".$data['where']['title']."'";
		}
		
		if(isset($data['where']['time_limit']) && $data['where']['time_limit'] != -1){
			$_where .= " and t3.time_limit = ".$data['where']['time_limit'];
		}
		
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		//排序
		$_order  = " order by t1.id desc ";
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_result .= $_where;
		$sql_result .= $_order;
		
		if(isset($data['limit']) && $data['limit'] == 'all'){
			$query = $this->db->query($sql_result);
			$data['tender_list'] = $query->result_array();
			return $data;
		}else{
			$sql_result .= " limit $page_start, $page_size";
			$query = $this->db->query($sql_result);
			$data['tender_list'] = $query->result_array();
		}	
		
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['tender_count'] = $query->row()->count;
		
		//投资总人数
		$sql_user_count = "select count(DISTINCT(t2.user_id)) as count from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_user_count .= $_where;
		$query = $this->db->query($sql_user_count);
		$data['tender_user_count'] = $query->row()->count;
		
		//投资金额
		$sql_money_sum = "select sum(t1.account) as count from rsh_borrow_tender as t1 left join rsh_user as t2 on t1.user_id=t2.user_id left join rsh_borrow as t3 on t1.borrow_id=t3.id";
		$sql_money_sum .= $_where;
		
		$query = $this->db->query($sql_money_sum);
		$data['tender_money_count'] = $query->row()->count;
		
		return $data;
	}
	
	
	function get_borrow_tender_lists($data = array()){
		$select = "t1.*";
		if(isset($data['select']) && $data['select'] == 1){
			$select = " t1.id,t1.user_id,t1.fstatus,t1.borrow_id,t1.money,t1.account,t1.repayment_account,t1.interest,
						t1.repayment_yesaccount,t1.repayment_yesinterest,t1.wait_account,t1.wait_interest,t1.add_time,
						t2.title,t2.apr,t2.time_limit,t2.is_day,t2.time_limit_day
						";
		}
		
		//封装条件
		$_where = " where 1=1 ";
		if(isset($data['where']['borrow_id']) && $data['where']['borrow_id'] >0){
			$_where .= " and t1.borrow_id = ".$data['where']['borrow_id'];
		}
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] != ''){
			$_where .= " and t2.fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['user_id']) && $data['where']['user_id'] > 0){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		
		//排序
		$_order  = " order by t1.id desc ";
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_tender as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$sql_result .= " limit $page_start, $page_size";
		$query = $this->db->query($sql_result);
		
		if(isset($data['list']) && $data['list'] == 1){
			return $query->result_array();
		}
		$data['tender_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow_tender as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['tender_count'] = $query->row()->count;
		return $data;
		
	}
	
	function get_borrow_tender($data = array()){
		$select = "id,user_id,fstatus,borrow_id,money,account,repayment_account,interest,
						repayment_yesaccount,repayment_yesinterest,
						wait_account,wait_interest,add_time";
		
		
		//封装条件
		$_where = " where 1=1 ";
		if(isset($data['where']['borrow_id']) && $data['where']['borrow_id'] >0){
			$_where .= " and borrow_id = ".$data['where']['borrow_id'];
		}
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] != ''){
			$_where .= " and fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['user_id']) && $data['where']['user_id'] > 0){
			$_where .= " and user_id = ".$data['where']['user_id'];
		}
		
		//排序
		$_order  = " order by id desc ";
		$_limit = "";
		if (isset($data['page'])){
			$page = intval($data['page']);
			$page = max($page,1);
			$_start = ($page-1)*20;
			$_limit = " limit {$_start},20";
		}
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_tender";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$sql_result .= $_limit;
		$query = $this->db->query($sql_result);
		$borrow_tender_list = $query->result_array();
		if(count($borrow_tender_list) < 1){
			return array();
		}
		return $borrow_tender_list;
	}
	
	function get_borrow_tender_2($data = array()){
		$select = "id,user_id,fstatus,borrow_id,money,account,repayment_account,interest,
						repayment_yesaccount,repayment_yesinterest,wait_account,wait_interest,add_time ";
		
		
		//封装条件
		$_where = " where 1=1 ";
		if(isset($data['where']['borrow_id']) && $data['where']['borrow_id'] >0){
			$_where .= " and borrow_id = ".$data['where']['borrow_id'];
		}
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] != ''){
			$_where .= " and fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['user_id']) && $data['where']['user_id'] > 0){
			$_where .= " and user_id = ".$data['where']['user_id'];
		}
		
		//排序
		$_order  = " order by id desc ";
		$page_start = $data['page_start'];
		$page_size 	= $data['page_size'];
		$_limit = "limit {$page_start}, {$page_size}";
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_tender";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$sql_result .= $_limit;
		$query = $this->db->query($sql_result);
		$borrow_tender_list = $query->result_array();
		if(count($borrow_tender_list) < 1){
			return array();
		}
		return $borrow_tender_list;
	}
	

	
	function get_borrow_count($data = array()){
		//封装条件
		$_where = " where 1=1 ";
		if(isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] != ''){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['ftype']) && $data['where']['ftype'] != ''){
			$_where .= " and t1.ftype = ".$data['where']['ftype'];
		}
		$sql_count = "select count(*) as count from rsh_borrow as t1 ";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		return $query->row()->count;
	}
	
	//根据时间获取当天的所有借款标数量
	function get_day_borrow($data = array()){
		//封装条件
		$_where = " where 1=1 ";
		if( !empty($data['where']['success_time']) ){
			$day = date('Y-m-d',$data['where']['success_time']);
			$day_start = strtotime($day." 00:00:00");
			$day_end = strtotime($day." 23:59:59");
			$_where .= " and success_time between '".intval($day_start)."' and '".intval($day_end)."'";
		}else{
			return array();
		}
		$_where .= ' order by id ASC ';
		$sql = "select id from rsh_borrow ";
		$sql .= $_where;
		$query = $this->db->query($sql);
		return $query->result_array();
	}
	
	//***** by liub 根据交易类型生成订单ID
	private function createOrderId($type){
		// 时间戳
		$orderid = time();
		// 生成3位随机数字
		$num = create_num(3);// 模拟毫秒数
		// 生成订单id
		$orderid =$type.'_'.$orderid.$num;
		
		return $orderid;
	}
	
	
	/**
	 * 投标
	 * tc-2014-11-19
	 * @param $data
	 */
	function borrow_tender($data = array()){
		$id 					= $data['id'];
		$account 				= $data['account'];
		$ip 					= $data['ip'];
		$user_id 				= $data['user_id'];
		$money 					= $data['money'];
		if($data['red_money']  && $data['red_money'] > 0) {
			$red_money	= $data['red_money'];
		}else {
			$red_money = 0;
		}
		$acou = $account-$red_money;//实际投标金额
		$borrow = self::get_borrow_obj($id);// 被投标的详情
		
		$this->load->model('Account_model');
		//var_dump($id);
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
    
		//添加用户资金使用记录
		$user_account = $this->Account_model->get_account($user_id);
		
		$log['user_id'] 		= $user_id;
		$log['ftype'] 			= TENDER;
		$log['money'] 			= $acou;
		$log['total'] 			= $user_account['total'];
		$log['use_money'] 		= $user_account['use_money']-$log['money'];
		$log['no_use_money'] 	= $user_account['no_use_money']+ $log['money'];
		$log['collection'] 		= $user_account['collection'];
		$log['op'] 		= 1;
		$log['remark'] 			= "投标冻结资金";
		$log['add_time'] 		= time();
		$log['addip'] 			= $ip;
		$mode = substr(strval($user_id),-1,1);
		$this->db->insert('rsh_account_log_'.$mode, $log);
		if($data['red_money'] && $data['red_money'] > 0){
			//添加用户代金卷消费记录
			$log['user_id'] 		= $user_id;
			$log['ftype'] 			= REDPACKAGE_DEDUCT;
			$log['money'] 			= $red_money;
			$log['total'] 			= $user_account['total'];
			$log['no_use_money'] 	= $user_account['no_use_money']+ $account;
			$log['collection'] 		= $user_account['collection'];
			$log['remark'] 			= "投标激活代金卷";
			$this->db->insert('rsh_account_log_'.$mode, $log);
		}
		
		//更新用户资金表
		// TODO by liub 20140102 代金卷总额加入资产中(并未到帐),注意原语句如下：
		//$this->db->query("update rsh_account set use_money=use_money-{$acou},no_use_money=no_use_money+{$account},red_money=red_money-{$red_money} where user_id={$user_id}");
		
		$this->db->query("update rsh_account set total = total + {$red_money},use_money=use_money-{$acou},
			no_use_money=no_use_money+{$account},red_money=red_money-{$red_money} where user_id={$user_id}");
		
		
		//更新投标表
		$this->db->query("update rsh_borrow set account_yes=account_yes+{$account},tender_times=tender_times+1 where id={$id}");
		//添加投标记录
		$t2data['user_id']  	= $user_id;
		$t2data['borrow_id ']  	= $id;
		$t2data['money']  		= $money;// 投标金额
		$t2data['account']  	= $acou; // 实投金额
		// $t2data['bf_trade_orderid']  	= $config_1['order_id'];// 订单ID
		$t2data['add_time']  	= time();
		$t2data['addip']  		= $ip;
		$t2data['fstatus']  	= '0';// 待审核

		$this->db->insert('rsh_borrow_tender', $t2data);
		$tender_id = $this->db->insert_id();
		
		$eq['account'] 			= $account;//投资金额 = 实投金额+红包金额
		// ****** 20141221 by liub 实现利率奖励
		$eq['apr'] 				= $borrow['apr'];//收益利率 = 定利率 + 奖励利率
		if($borrow['award'] == 1){
			//如果是月标，才能有$funds奖励
			if($borrow['is_day']!=1){
				$borrow['funds']=$borrow['funds']*12;
			}
			$eq['apr'] 				+= $borrow['funds'];
		}else{
		}//----------- end
		
		$eq['time_limit'] 		= $borrow['time_limit'];//投资期限
		$eq['style'] 			= $borrow['style'];//还款方式
        $eq['is_day']			= $borrow['is_day'];//是否是天标
        $eq['time_limit_day']	= $borrow['time_limit_day'];//天标天数
        // 必须加入 标的正常启标时间
        $eq['borrow_time'] 		= $borrow['bill_starttime'];//标的启标时间,以计算每期还款时间
        
        $eq['work_time'] = 0;
        if($borrow['work_time'] == 1){
        	$eq['work_time'] = floor(($borrow['bill_starttime']-time())/86400); //即时起息时间差
        }
        
        // ****************** 计算此投标的每期收益情况
		$result 				= equal_interest($eq);
		// *******************
		
		$repayment_account = 0;//应还本利
		foreach ($result as $key => $value){
			$repayment_account += $value['repayment_account'];// 应还本利= 本金+正常利息+即时利息
			//将投资归还信息写进去
			$bcdata['tender_id'] 	= $tender_id;
			$bcdata['borrow_id'] 	= $id;
			$bcdata['forder'] 		= $key;
			$bcdata['repay_time'] 	= $value['repayment_time'];
			$bcdata['repay_account']= $value['repayment_account'];
			$bcdata['work_interest'] 	= $value['worktime_interest'];
			
			$bcdata['interest'] 	= $value['interest'];
			$bcdata['capital'] 		= $value['capital'];
			$bcdata['user_id'] 		= $user_id;
			$bcdata['add_time'] 	= time();
			$bcdata['addip'] 		= $ip;
			$this->db->insert('rsh_borrow_collection', $bcdata);
		}
		//****** by liub 20150103 逻辑解释
		$_interest = $repayment_account-$account;//应还利息(正常利息+即时利息/利率奖励) = 应还本利 - 投资本金
		$this->db->query("update rsh_borrow_tender set repayment_account={$repayment_account},wait_account ={$repayment_account},interest = {$_interest},wait_interest = {$_interest} where id={$tender_id}");
		
		if ($this->db->trans_status() === TRUE) {
        	$this->db->trans_commit();
       	 	return 1;
   		 } else {
       	 	$this->db->trans_rollback();
        	return 0;
    	}
	}
	
	

	/**
	 * 及时计息投标
	 * @param $data
	 */
	function borrow_lz_tender($data = array()){
		$id 		= $data['id'];
		$ip 		= $data['ip'];
		$user_id 	= $data['user_id'];
		$money 		= $data['money'];
		$account 	= $data['account'];
		$red_money 	= $data['red_money'];
		$borrow 	= self::get_borrow_obj($data['id']);
		
		$this->load->model('Account_model');
		$this->load->model('User_model');
		$this->load->model('Message_model');
		
		$borrow_url 	= "<a href='/borrow/obj/{$borrow['id']}.html' target=_blank>{$borrow['title']}</a>";
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
		
		$this->db->query("update rsh_borrow set account_yes=account_yes+{$data['account']},tender_times=tender_times+1  where id='{$borrow['id']}'");

		$t2data['add_time']  	= time();
		$t2data['addip']  		= $ip;
		$t2data['user_id']  	= $user_id;
		$t2data['borrow_id ']  	= $id;
		$t2data['money']  		= $money;
		$t2data['account']  	= $account;
		$t2data['fstatus']  	= 1;
		
		
		$this->db->insert('rsh_borrow_tender', $t2data);
		$tender_id = $this->db->insert_id();
		
		if ($tender_id>0){
			//如果成功，则将还款信息输进表里面去
			$eq['account'] 			= $account;
			$eq['apr'] 				= $borrow['apr'];
			$eq['time_limit'] 		= $borrow['time_limit'];
			$eq['style'] 			= $borrow['style'];
	        $eq['is_day']			= $borrow['is_day'];
	        $eq['time_limit_day']	= $borrow['time_limit_day'];
			$result 				= equal_interest($eq);
			$repayment_account 		= 0;
			$collection_id = 0;
			foreach ($result as $key => $value){
				$repayment_account += $value['repayment_account'];
				//将归还信息写进去
				$this->db->query("insert into rsh_borrow_collection set user_id=$user_id,borrow_id=$id,add_time=".time().",addip='{$ip}',
						`tender_id`='{$tender_id}',`forder`='{$key}',`repay_time`='{$value['repayment_time']}',
						`repay_account`='{$value['repayment_account']}',`interest`='{$value['interest']}',
						`capital`='{$value['capital']}'");
			}
			$_interest = round($repayment_account-$data['account'],2);
			$this->db->query(" update rsh_borrow_tender set repayment_account='{$repayment_account}',
								wait_account ='{$repayment_account}',interest = '{$_interest}',
								wait_interest = '{$_interest}' where id={$tender_id}");
			
			//投标金额冻结
			$mode = substr(strval($user_id),-1,1);
			$account_result 	= $this->Account_model->get_account($user_id);
			$log['user_id'] 	= $user_id;
			$log['ftype'] 		= TENDER;
			$log['money'] 		= $account;
			$log['total'] 		= $account_result['total'];
			$log['use_money'] 	= $account_result['use_money']-$log['money'];
			$log['no_use_money']= $account_result['no_use_money']+$log['money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['op'] 	= 1;
			$log['remark'] 		= "投标冻结资金";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$user_id}");
			
			
			//扣除投资者的金钱。
			unset($account_result);
			unset($log);
			$account_result 	= $this->Account_model->get_account($user_id);
			$log['user_id'] 	= $user_id;
			$log['ftype'] 		= INVEST;
			$log['money'] 		= $account;
			$log['total'] 		= $account_result['total']-$log['money'];
			$log['use_money'] 	= $account_result['use_money'];
			$log['no_use_money']= $account_result['no_use_money']-$log['money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "投标成功费用扣除";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$user_id}");
			
			
			//添加待收的金额
			unset($account_result);
			unset($log);
			$account_result 	= $this->Account_model->get_account($user_id);
			$log['user_id'] 	= $user_id;
			$log['ftype'] 		= COLLECTION;
			$log['money'] 		= $repayment_account;
			$log['total'] 		= $account_result['total']+$log['money'];
			$log['use_money'] 	= $account_result['use_money'];
			$log['no_use_money']= $account_result['no_use_money'];
			$log['collection'] 	= $account_result['collection']+$log['money'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "待收金额";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$user_id}");
			
			
			
			//借款者总金额增加。		
			unset($account_result);
			unset($log);
			$mode1 = substr(strval($borrow['user_id']),-1,1);
			$account_result 	= $this->Account_model->get_account($borrow['user_id']);
			$log['user_id'] 	= $borrow['user_id'];
			$log['ftype'] 		= BORROW_SUCCESS;
			$log['money'] 		= $account;
			$log['total'] 		= $account_result['total']+$log['money'];
			$log['use_money'] 	= $account_result['use_money']+$log['money'];
			$log['no_use_money']= round($account_result['no_use_money'],2);
			$log['collection'] 	= round($account_result['collection'],2);;
			$log['to_user'] 	= "0";
			$log['remark'] 		= "通过[{$borrow_url}]借到的款";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode1, $log);
			$this->db->query("update rsh_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$borrow['user_id']}");			
			
		    $nowtime = time();
			$endtime = get_times(array("num"=>$borrow['time_limit'],"time"=>$nowtime));
			$_each_time = "每月".date("d",$nowtime)."日";
			$this->db->query("update rsh_borrow set success_time='{$nowtime}',end_time='{$endtime}',each_time='{$_each_time}',
					 			payment_account=payment_account+'{$repayment_account}'
					 			where id='{$borrow['id']}'");

			
			//更新标状态和复审时间复审备注
			if($borrow['account'] <= $borrow['account_yes']){
			//更新完成借款天数
				$borrowing_days = floor((time()-$borrow['verify_time'])/86400);
				$this->db->query("update rsh_borrow set fstatus=3,repayment_time=".time().",repayment_remark='及时计息自动复审',borrowing_days = $borrowing_days where id={$borrow['id']}");
			}
			$this->db->query("update rsh_borrow set account_yes=account_yes+{$data['account']},tender_times=tender_times+1  where id='{$borrow['id']}'");
			
		
			// ******  end
			
			//如果有设置奖励并且招标成功
			if ($borrow['funds'] > 0){
				//投标奖励扣除和增加。				
				if($borrow['award'] == 1){
					if($borrow['is_day'] == 1 ){
						$money = round((($borrow['funds']/100/360)*$borrow['time_limit_day']*$account),2);
					}else{
						$money = round((($borrow['funds']/100/12)*$account*$borrow['time_limit']),2);
					}
					
				}else{
					$money = $borrow['funds'];
				}
				
				unset($account_result);
				unset($log);
				$account_result 		= $this->Account_model->get_account($user_id);
				$log['user_id'] 		= $user_id;
				$log['ftype'] 			= AWARD_ADD;
				$log['money'] 			= $money;
				$log['total'] 			= $account_result['total']+$log['money'];
				$log['use_money'] 		= $account_result['use_money']+$log['money'];
				$log['no_use_money'] 	= round($account_result['no_use_money'],2);
				$log['collection'] 		= round($account_result['collection'],2);
				$log['to_user'] 		= $borrow['user_id'];
				$log['remark'] 			= "借款[{$borrow_url}]的奖励";
				$log['add_time'] 		= time();
				$log['addip'] 			= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$user_id}");
			
				unset($account_result);
				unset($log);
				$account_result 	= $this->Account_model->get_account($borrow['user_id']);
				$log['user_id'] 	= $borrow['user_id'];
				$log['ftype'] 		= AWARD_LOWER;
				$log['money'] 		= $money;
				$log['total'] 		= $account_result['total']-$log['money'];
				$log['use_money'] 	= $account_result['use_money']-$log['money'];
				$log['no_use_money'] 	= round($account_result['no_use_money'],2);
				$log['collection'] 		= round($account_result['collection'],2);
				$log['to_user'] 	= $user_id;
				$log['op'] 	= 1;
				$log['remark'] 		= "扣除借款[{$borrow_url}]的奖励";
				$log['add_time'] 	= time();
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$mode1, $log);
				$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");
			}
			
			
			if ($this->db->trans_status() === TRUE) {
		        $this->db->trans_commit();
		        return 1;
		    } else {
		        $this->db->trans_rollback();
		        //@todo 异常处理部分
		        return 0;
		    }
		}else{
			$this->db->trans_rollback();
			return 0;
		}
		
	}
	
	function reg_money_use($data=array()){
		$user_id = isset($data['user_id']) ? $data['user_id'] : 0;
		if ($user_id>0){
			$this->load->model('Account_model');
			$user_account = $this->Account_model->get_account($user_id);
			$log = array(
				'user_id' => $user_id,
				'ftype' => REG_MONEY,
				'money' => 100,
				'total' => $user_account['total'],
				'use_money' => $user_account['use_money']+100,
				'no_use_money' => $user_account['no_use_money'],
				'collection' => $user_account['collection'],
				'to_user' => 0,
				'add_time' => time(),
				'addip' => $this->js->get_ip(),
				'remark' => "注册礼金"
			);
			$mode = substr(strval($user_id),-1,1);
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$sql = "update rsh_account set use_money=use_money+100,reg_money=reg_money-100 where user_id={$user_id}";
			$query = $this->db->query($sql);
			return $this->db->affected_rows(); 
		}
	}
	
	
	// 获取标的用户实际投标总额
	private function getFullMoney($borrow_id,$fstatus){
		$_sql = " select sum(account) as sum_money from rsh_borrow_tender where borrow_id = {$borrow_id} and fstatus = {$fstatus} ";
		$query = $this->db->query($_sql);
		if($query->num_rows() > 0){
			return $query->row()->sum_money;
		}else{
			return 0 ;
		}
		
	}
	
	// 20141208 by liub
	/**
	 * 满标审核
	 * @param $data
	 */
	function zhs_borrow_review_true($data){
		$id 		= $data['id'];
		$ip 		= $data['ip'];
		$this->load->model('Account_model');
		$this->load->model('User_model');
		$this->load->model('Message_model');
		$this->load->model('Credit_model');
		$this->load->model('User_amount_model');
		
		$borrow = self::get_borrow_obj($id);

		// TODO by liub 20150203  红本需求结合 
		// 还款人
		$data['repayment_user'] = $borrow['user_id'];
		if ($borrow['fstatus'] != 1){
			return "此标已经审核过，不能再审核";
		}
		$repayment_account  	= $borrow['repayment_account'];
		$idata['account'] 		= $borrow['account'];
		
		// 利率变更
		$idata['apr'] 			= $borrow['apr'];
		if($borrow['award'] == 1){
			$idata['apr'] 		+= $borrow['funds'];
		}
		$idata['time_limit'] 	= $borrow['time_limit'];
		$idata['style'] 		= $borrow['style'];
        $idata['is_day']		= $borrow['is_day'];
        $idata['time_limit_day']= $borrow['time_limit_day'];
        
        // 必须加入 标的正常启标时间
        $idata['borrow_time'] 	= $borrow['bill_starttime'];//标的启标时间,计算每期还款时间
		$idata['work_time'] = 0;
        
		$result 				= equal_interest($idata);
		$total_account 			= 0;
		$borrow_url 	= "<a href='/borrow/obj/{$id}.html' target=_blank>{$borrow['title']}</a>";
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
		
		// 统计即时起息的利息
		$worksql = "select sum(work_interest) as work_interest from rsh_borrow_collection WHERE forder=0 AND borrow_id={$id} AND work_interest>0";
		$workquery = $this->db->query($worksql);
		$work_interest = $workquery->row()->work_interest;
		
		// 每笔还款信息
		foreach ($result as $key => $value){
			// 优化
			
			$brdata['borrow_id'] 		= $id;
			$brdata['user_id'] 			= $borrow['user_id'];//借款用户ID
			$brdata['forder'] 			= $key;
			$brdata['work_interest'] = 0;
			if($borrow['work_time'] == 1 && $key == 0){
				$brdata['work_interest'] 		= $work_interest;
	        }
			$brdata['repayment_time'] 	= $value['repayment_time'];
			$brdata['repayment_account']= $value['repayment_account']+$brdata['work_interest'];
			$brdata['interest'] 		= $value['interest'];
			$brdata['capital'] 			= $value['capital'];
			$brdata['add_time'] 		= time();
			$brdata['addip'] 			= $ip;
			$this->db->insert('rsh_borrow_repayment', $brdata);
			$repayment_account = $value['repayment_account'];
		}
		
		// 扣除所有投资者的金钱。
		$query = $this->db->query("select id,user_id,account,money,repayment_account,
			add_time from rsh_borrow_tender where fstatus = 0 and borrow_id=$id");
		$tender_list = $query->result_array();
		foreach ($tender_list as $tender){
			$this->db->query("update rsh_borrow_tender set fstatus=1 where id={$tender['id']}");			
			$user_info = $this->User_model->get_by_uid($tender['user_id']);
			//扣除冻结金额
			$mode = substr(strval($tender['user_id']),-1,1);
			$user_account = $this->Account_model->get_account($tender['user_id']);
			$log['user_id'] 		= $user_account['user_id'];
			$log['ftype'] 			= INVEST;//扣除冻结款
			$log['money'] 			= $tender['account'];
			$log['total'] 			= $user_account['total']-$log['money'];//投标时已加代金卷
			$log['use_money'] 		= $user_account['use_money'];
			$log['no_use_money'] 	= $user_account['no_use_money']-$log['money'];//减去投标金额(不含代金卷)
			$log['collection'] 		= $user_account['collection'];
			$log['to_user'] 		= $borrow['user_id'];
			$log['remark'] 			= "投标成功费用扣除";
			$log['add_time'] 		= time();
			$log['addip'] 			= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			// 修改 冻结金额 $this->db->query("update rsh_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tender['user_id']}");
			$this->db->query("update rsh_account set total=total-{$log['money']},
				no_use_money=no_use_money-{$tender['money']} where user_id={$tender['user_id']}");
			unset($user_account);
			unset($log);
			
			$red_money = $tender['money']-$tender['account'];
			//添加待收的金额
			$user_account = $this->Account_model->get_account($tender['user_id']);
			$log['user_id'] 		= $user_account['user_id'];
			$log['ftype'] 			= COLLECTION;//待收金额
			$log['money'] 			= $tender['repayment_account'];
			$total_account = $total_account+$tender['repayment_account'];//总还金额
			
			$log['total'] 			= $user_account['total']+$log['money'];
			$log['use_money'] 		= $user_account['use_money'];
			$log['no_use_money'] 	= $user_account['no_use_money'];
			$log['collection'] 		= $user_account['collection']+$log['money'];
			$log['to_user'] 		= $borrow['user_id'];
			$log['remark'] 			= "待收金额";
			$log['add_time'] 		= time();
			$log['addip'] 			= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			// ****** 总额 必须减去 已送代金卷(投标时已减)
			$this->db->query("update rsh_account set total=total+{$log['money']}-{$red_money},collection=collection+{$log['money']} where user_id={$tender['user_id']}");
			
			//提醒设置
			$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$tender['user_id'],
										'name'=>"投资的标[<font color=red>{$borrow['title']}</font>]满标审核成功",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"你所投资的标[<a href='/borrow/obj/{$borrow['id']}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在".date("Y-m-d",time())."已经审核通过",
										'add_time'=>time(),'addip'=>$ip));
			
		}

		//20150801 新注册用户投100元以上的月标，发放5元红包，每个用户限一次
		if($borrow['is_day']!=1){
			
		}

		// TODO 未完成：如果有设置现金奖励并且招标成功
		if ( $borrow['award'] == 2 && $borrow['funds'] > 0){
			// ****** by liub 20140102 每一个投资用户只奖励一次，即以第一次投资为准
			$query 	= $this->db->query("select user_id,account 
				from rsh_borrow_tender where borrow_id={$id} group by user_id order by id ");
			
			$tender_list 		= $query->result_array();
			$total_money_award 	= 0;
			foreach ($tender_list as $tender){
				unset($user_account);
				unset($log);
				$money = $borrow['funds'];
				$user_account = $this->Account_model->get_account($tender['user_id']);
				$log['user_id'] 		= $tender['user_id'];
				$log['ftype'] 			= AWARD_ADD;
				$log['money'] 			= $money;
				$log['total'] 			= $user_account['total']+$money;
				$log['use_money'] 		= $user_account['use_money']+$money;
				$log['no_use_money'] 	= $user_account['no_use_money'];
				$log['collection'] 		= $user_account['collection'];
				$log['to_user'] 		= $borrow['user_id'];
				$log['remark'] 			= "借款[{$borrow_url}]的奖励";
				$log['add_time'] 		= time();
				$log['addip'] 			= $ip;
				$mode = substr(strval($tender['user_id']),-1,1);
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$tender['user_id']}");
				// 提醒设置
				$this->Message_model->send(array('sent_user'=>$borrow['user_id'],'receive_user'=>$tender['user_id'],
										'name'=>"投标奖励发放",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"您收到投标奖励".$money,
										'add_time'=>time(),'addip'=>$ip));
				unset($user_account);
				unset($log);
				$user_account = $this->Account_model->get_account($borrow['user_id']);
				$log['user_id'] 		= $borrow['user_id'];
				$log['ftype'] 			= AWARD_LOWER;
				$log['money'] 			= $money;
				$log['total'] 			= $user_account['total']-$money;
				$log['use_money'] 		= $user_account['use_money']-$money;
				$log['no_use_money'] 	= $user_account['no_use_money'];
				$log['collection'] 		= $user_account['collection'];
				$log['to_user'] 		= 1;
				$log['op'] 	= 1;
				$log['remark'] 			= "扣除借款[{$borrow_url}]的奖励";
				$log['add_time'] 		= time();
				$log['addip'] 			= $ip;
				$mode = substr(strval($borrow['user_id']),-1,1);
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");
				$total_money_award += $money;
			}
			//提醒设置
			$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$borrow['user_id'],
										'name'=>"投标奖励发放",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"您共发放到投标奖励".$total_money_award,
										'add_time'=>time(),'addip'=>$ip));
		}
		
		//借款者总金额增加。
		$mode = substr(strval($borrow['user_id']),-1,1);
		$user_account = $this->Account_model->get_account($borrow['user_id']);
		$borrow_log['user_id'] 		= $borrow['user_id'];
		$borrow_log['ftype'] 		= BORROW_SUCCESS;
		$borrow_log['money'] 		= $borrow['account'];
		$borrow_log['total'] 		= $user_account['total']+$borrow_log['money'];
		$borrow_log['use_money'] 	= $user_account['use_money']+$borrow_log['money'];
		$borrow_log['no_use_money'] = $user_account['no_use_money'];
		$borrow_log['collection'] 	= $user_account['collection'];
		$borrow_log['to_user'] 		= $borrow['user_id'];
		$borrow_log['remark'] 		= "通过[{$borrow_url}]借到的款";
		$borrow_log['add_time'] 	= time();
		$borrow_log['addip'] 		= $ip;
		$this->db->insert('rsh_account_log_'.$mode, $borrow_log);
		$this->db->query("update rsh_account set total=total+{$borrow_log['money']},use_money=use_money+{$borrow_log['money']} where user_id={$borrow['user_id']}");
		
		
		//TODO 20150317 发送满标站内信给借款者
		$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$borrow['user_id'],
										'name'=>"您借款的标[<font color=red>{$borrow['title']}</font>]满标审核成功",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"您借款的标[<a href='/borrow/obj/{$borrow['id']}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在".date("Y-m-d",time())."已经审核通过",
										'add_time'=>time(),'addip'=>$ip));
		
		//更新满标时的操作人
		$nowtime = time();
		$endtime = get_times(array("num"=>$borrow['time_limit'],"time"=>$nowtime));
		if($borrow['is_day'] == 1){
			$endtime = time() + $borrow['time_limit_day']*60*60*24;
		}
		$this->db->query("update rsh_borrow set success_time={$nowtime},end_time={$endtime}   where id={$id}");
		
		// 更新满标时的操作人和完成借款天数
		$borrowing_days = floor((time()-$borrow['auto_verify_time'])/86400);
		$this->db->query("update rsh_borrow set borrowing_days={$borrowing_days},repayment_user={$data['repayment_user']},repayment_account={$total_account},repayment_remark='{$data['repayment_remark']}',repayment_time='".time()."',fstatus=3 where id={$id}");
		
		if ($this->db->trans_status() === TRUE) {
        	$this->db->trans_commit();
       	 	return 1;
    	} else {
        	$this->db->trans_rollback();
        	return 0;
    	}
	}
	
	/**
	 * 满标复审(弃用)
	 * @param $data
	 */
	function borrow_review_true($data){
		$id 		= $data['id'];
		$ip 		= $data['ip'];
		$this->load->model('Account_model');
		$this->load->model('User_model');
		$this->load->model('Message_model');
		$this->load->model('Credit_model');
		$this->load->model('User_amount_model');
		$borrow = self::get_borrow_obj($id);
		if ($borrow['fstatus'] != 1){
			return "此标满标复审已审核过，不能再审核";
		}
		
		/*
		// ****** 20141227 by liub 资金托管：满标
		
		$actions = array();
		// 借款人
		$config['user_id']		= $borrow['user_id'];
		$config['amount'] 		= $borrow['account'];
		$config['fee'] 			=  0;// 满标手续费目前为0 
		$config['is_voucher'] 	= "0"; // 借款人唯一标记，其他为null
		$config['special'] 		= null;
		$this->load->library('baofooSdk/dto/request/Action',$config,'action');
		
		array_push($actions,object_to_array($this->action));
		// 暂无担保人,略过
		$config_1['merchant_id'] 	= MERCHANT_ID;
		$config_1['action_type'] 	= "2";// 投标为1，满标为2，流标为3，还标为4
		$config_1['order_id'] 		= self::createOrderId($config_1['action_type'] );
		$config_1['cus_id'] 		= $borrow['user_id'];
		$config_1['cus_name'] 		= $borrow['id'];
		$config_1['brw_id'] 		= $borrow['id'];
		$config_1['req_time'] 		= strtotime(date("Y-m-d H:i:s")).'000';// 13位
		$config_1['fee'] 			= "0";
		$config_1['actions'] 		= $actions;
		$this->load->library('baofooSdk/dto/request/P2pRequestDto',$config_1,'p2pRequestDto');
		$this->load->library('baofooSdk/BaofooRequestService',0,'br');
		
		$result = $this->br->api_P2pRequest($this->p2pRequestDto);
		
		if($result['code'] == 'CSD000'){
			$this->db->query("update rsh_borrow set bf_result_code='{$result['code']}',bf_trade_status = 1 where id={$id}");
			//return 1;
		}else{
			$this->db->query("update rsh_borrow set bf_result_code='{$result['code']}',bf_trade_status = 2 where id={$id}");
			return 0;
		}
		*/
		
		
		$repayment_account  	= $borrow['repayment_account'];
		
		// ------- by liub 2014122
		$idata['account'] 		= $borrow['account'];//金额
		$idata['apr'] 			= $borrow['apr'];//利率
		if($idata['award'] == 0){
			$idata['apr'] 		+= $borrow['funds'];
		}else{
		}
		$idata['time_limit'] 	= $borrow['time_limit'];// 月份
		$idata['style'] 		= $borrow['style'];// 还款类型
        $idata['is_day']		= $borrow['is_day'];// 是否是天标
        $idata['time_limit_day']= $borrow['time_limit_day'];//天标天数
        $idata['borrow_time'] 	= $borrow['bill_starttime'];//标的启标时间,计算每期还款时间
        // ------- end
		$result 				= equal_interest($idata);
		$total_account 			= 0;
		$borrow_url 	= "<a href='/borrow/obj/{$id}.html' target=_blank>{$borrow['title']}</a>";
		
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
		foreach ($result as $key => $value){
			$total_account = $total_account+$value['repayment_account'];//总还金额
			$brdata['borrow_id'] 		= $id;
			$brdata['user_id'] 			= $borrow['user_id'];
			$brdata['forder'] 			= $key;//还款分期数
			$brdata['repayment_time'] 	= $value['repayment_time'];//每期还款时间
			$brdata['repayment_account']= $value['repayment_account'];//每期还款金额
			$brdata['interest'] 		= $value['interest'];// 每期利息
			$brdata['capital'] 			= $value['capital']; // 每期本金
			$brdata['add_time'] 		= time();
			$brdata['addip'] 			= $ip;
			$this->db->insert('rsh_borrow_repayment', $brdata);
			$repayment_account = $value['repayment_account'];
		}
		
		//扣除所有投资者的金钱。
		$query = $this->db->query("select id,user_id,account,repayment_account,add_time from rsh_borrow_tender where fstatus = 0 and borrow_id=$id");
		$tender_list = $query->result_array();
		foreach ($tender_list as $tender){
			$this->db->query("update rsh_borrow_tender set fstatus=1 where id={$tender['id']}");			
			$user_info = $this->User_model->get_by_uid($tender['user_id']);
			// 扣除投资者冻结金额
			// by liub 20141203
			$mode = substr(strval($tender['user_id']),-1,1);
			$user_account = $this->Account_model->get_account($tender['user_id']);
			$log['user_id'] 		= $user_account['user_id'];
			$log['ftype'] 			= INVEST;//扣除冻结款
			$log['money'] 			= $tender['account'];
			$log['total'] 			= $user_account['total']-$log['money'];
			$log['use_money'] 		= $user_account['use_money'];
			$log['no_use_money'] 	= $user_account['no_use_money']-$log['money'];
			$log['collection'] 		= $user_account['collection'];
			$log['to_user'] 		= $borrow['user_id'];
			$log['remark'] 			= "投标成功费用扣除";
			$log['add_time'] 		= time();
			$log['addip'] 			= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tender['user_id']}");
			
			unset($user_account);
			unset($log);
			//添加待收的金额
			$user_account = $this->Account_model->get_account($tender['user_id']);
			$log['user_id'] 		= $user_account['user_id'];
			$log['ftype'] 			= COLLECTION;//待收金额
			$log['money'] 			= $tender['repayment_account'];
			$log['total'] 			= $user_account['total']+$log['money'];
			$log['use_money'] 		= $user_account['use_money'];
			$log['no_use_money'] 	= $user_account['no_use_money'];
			$log['collection'] 		= $user_account['collection']+$log['money'];
			$log['to_user'] 		= $borrow['user_id'];
			$log['remark'] 			= "待收金额";
			$log['add_time'] 		= time();
			$log['addip'] 			= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$tender['user_id']}");
			
			// 提醒设置
			$this->Message_model->send(array('sent_user'=>$borrow['user_id'],'receive_user'=>$tender['user_id'],
										'name'=>"投资的标[<font color=red>{$borrow['title']}</font>]满标审核成功",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"你所投资的标[<a href='/borrow/obj/{$borrow['id']}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在".date("Y-m-d",time())."已经审核通过",
										'add_time'=>time(),'addip'=>$ip));
			
			// 更新投资人的投标标的还款日期
		}
		
		//借款者总金额增加。
		$mode = substr(strval($borrow['user_id']),-1,1);
		$user_account = $this->Account_model->get_account($borrow['user_id']);
		$borrow_log['user_id'] 		= $borrow['user_id'];
		$borrow_log['ftype'] 		= BORROW_SUCCESS;
		$borrow_log['money'] 		= $borrow['account'];
		$borrow_log['total'] 		= $user_account['total']+$borrow_log['money'];
		$borrow_log['use_money'] 	= $user_account['use_money']+$borrow_log['money'];
		$borrow_log['no_use_money'] = $user_account['no_use_money'];
		$borrow_log['collection'] 	= $user_account['collection'];
		$borrow_log['to_user'] 		= "1";
		$borrow_log['remark'] 		= "通过[{$borrow_url}]借到的款";
		$borrow_log['add_time'] 	= time();
		$borrow_log['addip'] 		= $ip;
		$this->db->insert('rsh_account_log_'.$mode, $borrow_log);
		$this->db->query("update rsh_account set total=total+{$borrow_log['money']},use_money=use_money+{$borrow_log['money']} where user_id={$borrow['user_id']}");
			
		// 更新满标时的操作人
		$nowtime = time();
		$endtime = get_times(array("num"=>$borrow['time_limit'],"time"=>$nowtime));
		$_each_time = $nowtime;
		if($borrow['is_day'] == 1){
			$endtime = time()+$borrow['time_limit_day']*60*60*24;
			$_each_time = $endtime;
		}
		$this->db->query("update rsh_borrow set success_time={$nowtime},end_time={$endtime},payment_account={$repayment_account} where id={$id}");
				
		// 更新满标时的操作人和完成借款天数
		$borrowing_days = floor((time()-$borrow['auto_verify_time'])/86400);
		
		$this->db->query("update rsh_borrow set borrowing_days={$borrowing_days},repayment_user={$data['repayment_user']},repayment_account={$total_account},repayment_remark='{$data['repayment_remark']}',repayment_time='".time()."',fstatus=3 where id={$id}");
		if ($this->db->trans_status() === TRUE) {
	        $this->db->trans_commit();
	        return 1;
	    } else {
	        $this->db->trans_rollback();
	        //@todo 异常处理部分
	        return 0;
	    }
	}
	
	/**
	 * 复审不通过
	 * @param $data
	 */
	function borrow_review_false($data){
		$id 		= $data['id'];
		$ip 		= $data['ip'];
		$fstatus	= $data['fstatus'];
		
		$this->load->model('Account_model');
		$this->load->model('Message_model');
		$borrow 		= self::get_borrow_obj($id);
		$borrow_url 	= "<a href='/borrow/obj/{$id}.html' target=_blank>{$borrow['title']}</a>";
		//返回所有投资者的金钱。
		$query = $this->db->query("select id,user_id,account,repayment_account,jiaoyan,add_time from rsh_borrow_tender where borrow_id={$id}");
		$tender_list = $query->result_array();
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
    
		foreach ($tender_list as $tender){
			$mode = $tender['user_id']%100;
			$user_account = $this->Account_model->get_account($tender['user_id']);
			$log['user_id'] 	= $tender['user_id'];
			$log['ftype'] 		= INVEST_FALSE;
			$log['money'] 		= $tender['account'];
			$log['total'] 		= $user_account['total'];
			$log['use_money'] 	= $user_account['use_money']+$log['money'];
			$log['no_use_money']= $user_account['no_use_money']-$log['money'];
			$log['collection'] 	= $user_account['collection'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "招标[{$borrow_url}]失败返回的投标额";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tender['user_id']}");
			if($tender['jiaoyan'] != 1){
				 $this->db->query("update rsh_borrow_tender set jiaoyan=1 where borrow_id={$id} and id={$tender['id']}");
			}
			$this->db->query("update rsh_borrow_collection set fstatus=2 where tender_id={$tender['id']}");
			$this->db->query("update rsh_borrow_tender set fstatus=2 where id={$tender['id']}");
			//提醒设置
			$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$tender['user_id'],
										'name'=>"投资的标[<font color=red>{$borrow['title']}</font>]满标审核失败",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"你所投资的标[<a href='/borrow/obj/{$id}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在".date("Y-m-d",time())."审核失败,失败原因：{$data['repayment_remark']}",
										'add_time'=>time(),'addip'=>$ip));
		}
		$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$borrow['user_id'],
										'name'=>"你所申请的标[<font color=red>{$borrow['title']}</font>]满标审核失败",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"你所申请的标[<a href='/borrow/obj/{$data['id']}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在".date("Y-m-d",time())."审核失败,失败原因：{$data['repayment_remark']}",
										'add_time'=>time(),'addip'=>$ip));
		
		$this->db->query("update rsh_borrow set repayment_user={$data['repayment_user']},repayment_remark='{$data['repayment_remark']}',repayment_time='".time()."',fstatus=4 where id={$id}");
		if ($this->db->trans_status() === TRUE) {
	        $this->db->trans_commit();
	        return 1;
	    } else {
	        $this->db->trans_rollback();
	        //@todo 异常处理部分
	        return 0;
	    }
	}
	
	/**
	 * 查询
	 * @param $data
	 */
	function get_borrow_list($data){
		//封装查询内容
		
		$select = "*";
		if($data['select'] == 1){
			$select = " id, user_id, title, account, apr, funds, time_limit , 
						style, is_dxb, account_yes/account as scales, summary,  
						fstatus, ftype, award,time_limit_day, verify_time,is_kjb,
						account_yes, valid_time, end_time, lowest_account,most_account,
						repayment_account,repayment_yesaccount, title_img,tender_times ";
		}elseif($data['select'] == 2){
			$select = "user_id,id,title,verify_time, summary,  repayment_time,fstatus,account_yes/account as scales";
		}
		
		//封装条件
		$_where = " where 1=1 ";
		if (isset($data['where']['is_index']) && $data['where']['is_index']==1 && !isset($data['where']['is_yjb'])){
			$_where .= " and ftype != 6";
		}
		if (isset($data['where']['is_yjb']) && $data['where']['is_yjb']==1){
			//$_where .= " and ftype = 6 and account<account_yes";
			$_where .= " and ftype = 6";
		}
		if (isset($data['where']['is_index']) && $data['where']['is_index']==1 && !isset($data['where']['is_kjb'])){
			$_where .= " and is_kjb = 0";
		}
		if (isset($data['where']['is_kjb']) && $data['where']['is_kjb']==1){
			$_where .= " and is_kjb = 1";
		}
		
		if(isset($data['where']['keywords']) && $data['where']['keywords'] != ''){
			$_where .= " and title like '%".$data['where']['keywords']."%'";
		}
		if(isset($data['where']['time_limit']) && $data['where']['time_limit'] >0){
			$_where .= " and time_limit = ".$data['where']['time_limit'];
		}
		if(isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and user_id = ".$data['where']['user_id'];
		}
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] != ''){
			$_where .= " and fstatus = ".$data['where']['fstatus'];
		}else{
			//$_where .= " and (fstatus = 1 or fstatus = 3)";
		}
		if(isset($data['where']['qtype']) && $data['where']['qtype'] != ''){
			$now_times = time();
			if($data['where']['qtype'] == 'index'){
				$_where .= " and (ftype!=4 and fstatus=1) or (ftype=4 and account>account_yesand fstatus in (1,3))";	
			}elseif($data['where']['qtype'] == 'now'){
				$_where .= " and repayment_account != repayment_yesaccount and fstatus=3";	
			}elseif($data['where']['qtype'] == 'yes'){
				$_where .= " and repayment_account = repayment_yesaccount and fstatus=3 ";	
			}elseif($data['where']['qtype'] == 'late'){
				$_where .= " and ftype!=4 and repayment_account != repayment_yesaccount and 
							 fstatus=3 and end_time<".(time()+12*60*60);	
			}
		}else{
			if (isset($data['where']['is_kjb']) && $data['where']['is_kjb']==1){
				$_where .= " and fstatus in (1)";	
			}elseif (isset($data['where']['is_yjb']) && $data['where']['is_yjb']==1){
				$_where .= " and fstatus in (1,3)";
			}else{
				$_where .= " and (fstatus=1 or (ftype!=4 and fstatus=3 and repayment_account!=repayment_yesaccount)
						or ((ftype=4 or ftype=5) and fstatus in (1,3))) ";	
			}
			
		}
		if(isset($data['where']['ftype']) && $data['where']['ftype'] > 0){
			$_where .= " and ftype = ".$data['where']['ftype'];
		}
		
		
		
		//排序
		$_order  = " order by fstatus asc,id desc ";
		if(isset($data['where']['order']) && $data['where']['order'] == 'index'){
			$_order  = " order by fstatus asc,verify_time desc,id desc ";
		}
		if (isset($data['where']['order']) && $data['where']['order'] == 'yjb'){
			$_order  = " order by id desc";
		}
		if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'now'){
			$_order  = " order by id desc ";
		}
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		$sql_result = "select $select from rsh_borrow";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$sql_result .= " limit $page_start, $page_size";//echo $sql_result;exit;

		$query = $this->db->query($sql_result);
		
		if(isset($data['list']) && $data['list'] == 1){
			return $query->result_array();
		}
		$data['borrow_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['borrow_count'] = $query->row()->count;
		return $data;
	}
	
	function get_borrow_blist($data){
		//封装查询内容
		$select = "bor.*,con.thumbnail";
		if($data['select'] == 1){
			$select = " bor.*,con.thumbnail";		
		}
		//封装条件
		$ctime = time();
		if(isset($data['where']['srate'])){
			$_where =  ' where 1=1 ';
			if ($data['where']['srate']==1){
				$_where .= " and bor.fstatus = 1";
			}elseif ($data['where']['srate']==3){
				$_where .= " and bor.fstatus = 3 and bor.account = bor.account_yes ";
			}else{
				$_where .= " and (bor.fstatus in(1,3,5) )"; 
			}
		}else{
			$_where = " where (bor.fstatus in(1,5) )"; 
		}
		/*
		if(isset($data['where']['time_limit']) && $data['where']['time_limit'] >0){
			$_where .= " and bor.time_limit = ".$data['where']['time_limit'];
		}*/
		if(isset($data['where']['ftype']) && $data['where']['ftype'] > 0){
			$_where .= " and bor.ftype = ".$data['where']['ftype'];
		}
		if (isset($data['where']['sftype']) && $data['where']['sftype']>0){
			$_where .= " and bor.ftype = ".$data['where']['sftype'];
		}
		if (isset($data['where']['saccount'])){
			if ($data['where']['saccount']==1){
				$_where .= " and bor.account<100000";
			}elseif ($data['where']['saccount']==2){
				$_where .= " and bor.account>=100000 and bor.account<200000";
			}elseif ($data['where']['saccount']==3){
				$_where .= " and bor.account>=200000 and bor.account<500000";
			}elseif ($data['where']['saccount']==4){
				$_where .= " and bor.account>=500000 and  bor.account<1000000";
			}elseif ($data['where']['saccount']==5){
				$_where .= " and bor.account>=1000000";
			}
		}
		if (isset($data['where']['sapr'])){
			if ($data['where']['sapr']==1){
				$_where .= " and bor.apr<12";
			}elseif ($data['where']['sapr']==2){
				$_where .= " and bor.apr>=12 and bor.apr<20";
			}elseif ($data['where']['sapr']==3){
				$_where .= " and bor.apr>=20";
			}
		}
		
		if(isset($data['where']['id'])){//数组
			$ids = implode(',',$data['where']['id']);
			$_where .= " and bor.id in (".$ids.") ";
		}
		
		if (isset($data['where']['slimit'])){
			// "1"=>"1个月以下", "2"=>"1~3个月", "3"=>"3~6个月", "4"=>"6~12个月",  "5"=>"12个月以上",
			if ($data['where']['slimit']==1){
				$_where .= " and ( bor.time_limit <= 1 and  bor.time_limit_day <= 30 ) ";
			}elseif ($data['where']['slimit']==2){
				$_where .= " and ((bor.time_limit>=1 and bor.time_limit<=3) or ( bor.time_limit_day >= 30 and bor.time_limit_day <= 90 )) ";
			}elseif ($data['where']['slimit']==3){
				$_where .= " and ((bor.time_limit>=3 and bor.time_limit<=6) or ( bor.time_limit_day >= 90 and bor.time_limit_day <= 180 )) ";
			}elseif ($data['where']['slimit']==4){
				$_where .= " and ((bor.time_limit>=6 and bor.time_limit<=12) or ( bor.time_limit_day >= 180 and bor.time_limit_day <= 360 ))";
			}elseif ($data['where']['slimit']==5){
				$_where .= " and ((bor.time_limit > 12  and bor.time_limit_day > 360))";
			}
		}
		
		if (isset($data['where']['style'])){
			if ($data['where']['style']==1){
				$_where .= " and style = 1 ";
			}elseif ($data['where']['style']==2){
				$_where .= " and style = 2 ";
			}elseif ($data['where']['style']==3){
				$_where .= " and style = 3 ";
			}
		}
			$_order  = " order by account_yes/account asc,bor.id desc ";
			
		if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'now'){
				$_order  = " order by bor.id ASC ";
			}
			
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		$sql_result = "select $select from rsh_borrow as bor left join rsh_borrow_conset_credit as con on bor.fsafe=con.id";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$sql_result .= " limit $page_start, $page_size";
		//echo $sql_result;exit;
		$query = $this->db->query($sql_result);
		if(isset($data['list']) && $data['list'] == 1){
			return $query->result_array();
		}
		$data['borrow_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow as bor left  join rsh_borrow_conset_credit as con on bor.fsafe=con.id";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['borrow_count'] = $query->row()->count;
		return $data;
	}
	
	
	
	//TODO ****** by liub  20141209 
	function get_zhs_index_borrow($data){
		// 适用手机端查询
		$_sql = "select * from rsh_borrow ";
		if(isset($data['where']['flag'])){
			if (isset($data['where']['flag']) && $data['where']['flag'] !=''){
				//$_where .= " and bor.is_verify = ".$data['where']['is_verify'];
				if($data['where']['flag'] =='passing'){// 理财中 或者审核中
					$_where .= " where (fstatus = 1 or fstatus = 3)  and account >= account_yes ";
				}elseif($data['where']['flag'] =='going'){
					$_where .= " where  fstatus = 0 ";// 即将上线
				}
			}
			if (isset($data['where']['is_check']) && $data['where']['is_check']>=0){
				$_where .= " and is_check = ".$data['where']['is_check'];
			}
			if (isset($data['where']['is_verify']) && $data['where']['is_verify']>=0){
				$_where .= " and is_verify = ".$data['where']['is_verify'];
			}
		}
		//排序
		//$_order  = "  order by ftype desc,id desc ";
		$_order  = " order by account_yes/account asc,id desc ";
		
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		$sql_result = $_sql.$_where;
		$sql_result .= $_order;
		$sql_result .= " limit $page_start, $page_size";
		
		//echo $sql_result;exit;
		$query = $this->db->query($sql_result);
		$data['borrow_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['borrow_count'] = $query->row()->count;
		return $data;
	}
	
	//逾期还款列表
	function get_late_list($data = array()){
		$select = "p1.id,p1.user_id,p1.repayment_time,p1.capital,p1.late_days,p1.late_interest,p1.repayment_account,
					p2.realname,p2.phone,p2.email,p2.qq,p2.sex,p2.card_id,p2.province,p2.city,p2.area";
		//封装条件
		if(isset($data['where']['late_day']) && $data['where']['late_day'] != ''){
			$_repayment_time = time()-60*60*24*$data['late_day'];
		}else{
			$_repayment_time = time();
		}
		$_where = " where p1.repayment_time < ".time()." and p1.fstatus!=1 and p1.borrow_id>0";
		//排序
		$_order  = " order by p1.id desc ";
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_repayment as p1 left join rsh_user as p2 on p1.user_id=p2.user_id ";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$query = $this->db->query($sql_result);
		
		if(isset($data['list']) && $data['list'] == 1){
			return $query->result_array();
		}
		$late_list1 = $query->result_array();
		$late_list = array();
		foreach ($late_list1 as $key => $value){
			$late = late_interest($value['repayment_time'], $value['capital']);
			$late_list[$value['user_id']]['realname'] = $value['realname'];
			$late_list[$value['user_id']]['phone'] = $value['phone'];
			$late_list[$value['user_id']]['user_id'] = $value['user_id'];
			$late_list[$value['user_id']]['email'] = $value['email'];
			$late_list[$value['user_id']]['qq'] = $value['qq'];
			$late_list[$value['user_id']]['sex'] = $value['sex'];
			$late_list[$value['user_id']]['card_id'] = $value['card_id'];
			$late_list[$value['user_id']]['province'] = $value['province'];
			$late_list[$value['user_id']]['city'] = $value['city'];
			$late_list[$value['user_id']]['area'] = $value['area'];
			$late_list[$value['user_id']]['late_days'] = $late['late_days'];//总逾期天数
			if (@$late_list[$value['user_id']]['late_numdays'] < $late['late_days']){
				$late_list[$value['user_id']]['late_numdays'] =  $late['late_days'];
			}
			@$late_list[$value['user_id']]['late_interest'] += round($late['late_interest']/2,2);
			@$late_list[$value['user_id']]['late_account'] +=  $value['repayment_account'];//逾期总金额
			@$late_list[$value['user_id']]['late_num'] ++;//逾期笔数
			@$late_list[$value['user_id']]['late_webnum'] = 0;//逾期笔数
		}
		
		$data['late_list'] = $late_list;
		//总记录条数
		$data['late_count'] = count($late_list);
		return $data;
	}
	
	/**
	 * 查询
	 * @param $data
	 */
	function admin_get_borrow_list($data){
		//封装查询内容
		$select = "*";
		if($data['select'] == 1){
			$select = "t1.id, t1.user_id, t1.title, t1.account , t1.apr, t1.funds, t1.time_limit , t1.style,
						t1.fstatus, t1.ftype, t1.award, t1.verify_time, t1.account_yes, t1.valid_time ";
		}
		
		//封装条件
		//$_where = " where 1=1 ";
		$_where="";
		if(isset($data['where']['title']) && $data['where']['title'] != ''){
			$_where .= " and t1.title like '%".$data['where']['title']."%'";
		}
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] != ''){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'full'){
			$_where .= " and t1.account = t1.account_yes and t1.fstatus=1 ";
		}
		if(isset($data['where']['ftype']) && $data['where']['ftype'] != ''){
			$_where .= " and t1.ftype = ".$data['where']['ftype'];
		}
		
		//排序
		$order  = " order by t1.id desc ";
		if(isset($data['where'])){
			if($data['order'] == 'verify'){
				$order  = " order by t1.verify_time desc,t1.id desc ";	
			}
		}		
		
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		$sql_result = "select $select from rsh_borrow as t1 ";
		$sql_result .= $_where;
		$sql_result .= $order;
		$sql_result .= " limit $page_start, $page_size";
		$query = $this->db->query($sql_result);
		$data['borrow_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow as t1 ";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['borrow_count'] = $query->row()->count;
		return $data;
	}
	
	/**
	 * 查询
	 * @param $data
	 */

	function get_borrow_user_list($data){
		//封装查询内容
		$select = "*";
		if($data['select'] == 1){
			$select = "id, title, account , apr, funds, style,fstatus,ftype,add_time,verify_time,
				auto_verify_time,account_yes,lowest_account,most_account,is_check,is_verify,bill_starttime,
				bill_endtime,each_time,tender_times,hits,fsafe,work_time,time_limit,is_day,time_limit_day,borrowing_days";
		}
		
		//封装条件
		$_where = " where 1=1 ";
		if(isset($data['where']['title']) && $data['where']['title'] != ''){
			$_where .= " and title like '%".$data['where']['title']."%'";
		}
		
		if(isset($data['where']['fstatus'])){
			$_where .= " and fstatus = ".$data['where']['fstatus'];
		}
		
		if(isset($data['where']['style']) && $data['where']['style'] != ''){
			$_where .= " and style = ".$data['where']['style'];
		}
		
		
		if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'full'){//满标待审核
			$_where .= " and account = account_yes and fstatus=1 ";
		}else if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'passing'){//标的已还款，标已结束
			$_where .= " and fstatus = 3 and repayment_account <= repayment_yesaccount ";
		}else if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'refunding'){//还款中的标的
			$_where .= " and fstatus = 3 and repayment_account > repayment_yesaccount ";
		}else if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'first'){//待初检
			$_where .= " and fstatus = 0 and is_check !=1 and is_verify = 0 ";
		}else if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'again'){//待复检
			$_where .= " and fstatus = 0 and is_check = 0 and is_verify = 1 ";
		}else if(isset($data['where']['qtype']) && $data['where']['qtype'] == 'publish'){//(初、复检成功)待发布
			$_where .= " and fstatus = 0 and is_check = 1 and is_verify = 1 ";
		}
		//echo $_where;exit;
		if(isset($data['where']['ftype']) && $data['where']['ftype'] != ''){
			$_where .= " and ftype = ".$data['where']['ftype'];
		}
		
		
		if (isset($data['where']['is_check']) && $data['where']['is_check'] > 0) {
            $_where .= " and is_check = " . $data['where']['is_check'];
        }
        
		if (isset($data['where']['is_verify']) && $data['where']['is_verify'] > 0) {
            $_where .= " and is_verify >= " . $data['where']['is_verify'];
        }
        
		if (isset($data['where']['auto_verify_time']) && $data['where']['auto_verify_time'] > 0) {
            $_where .= " and auto_verify_time <= " . $data['where']['auto_verify_time'];
        }
        
		if (isset($data['where']['work_time']) && $data['where']['work_time'] > 0) {
            $_where .= " and work_time = " . $data['where']['work_time'];
        }
        
        if (isset($data['where']['id']) && $data['where']['id'] > 0) {
            $_where .= " and id = " . $data['where']['id'];
        }
        //echo $_where;exit;
		
		//排序
		$order  = " order by id desc ";
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		
		$sql_result = "select $select from rsh_borrow ";
		$sql_result .= $_where;
		$sql_result .= $order;
		$sql_result .= " limit $page_start, $page_size";
		
		//echo $_where;
		
		$query = $this->db->query($sql_result);
		$data['borrow_list'] = $query->result_array();

		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow ";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['borrow_count'] = $query->row()->count;

		return $data;
	}
	
	function get_borrow_verify_list($data){
		//封装查询内容
		$select = "*";
		if($data['select'] == 1){
			$select = "id, title, account , apr, funds, style,fstatus,ftype,add_time,verify_time,account_yes,lowest_account,most_account,is_check,is_verify,bill_starttime,bill_endtime,each_time,tender_times,hits,fsafe,work_time,time_limit,is_day,time_limit_day";
		}
		
		//封装条件
		$_where = " where 1=1 ";
		$_where .= " and fstatus = 0 ";
		
		if(isset($data['where']['ftype']) && $data['where']['ftype'] != ''){
			$_where .= " and ftype = ".$data['where']['ftype'];
		}
				
		//排序
		$order  = " order by id desc ";
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		
		$sql_result = "select $select from rsh_borrow ";
		$sql_result .= $_where;
		$sql_result .= $order;
		$sql_result .= " limit $page_start, $page_size";
		$query = $this->db->query($sql_result);
		$data['borrow_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow ";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['borrow_count'] = $query->row()->count;
		return $data;
	}
	
	function get_repayment_list($data){
		//封装查询内容
		$select = "*";
		if(isset($data['select']) && $data['select'] == 1){
			$select = " t1.id, t1.user_id, t1.fstatus, t1.forder, t1.borrow_id, t1.repayment_time, t1.repayment_yestime,
						t1.repayment_account, t1.repayment_yesaccount, t1.interest, t1.capital, t1.late_days, 
						t1.late_interest, t2.id as borrow_id,t2.fstatus, t2.title,t2.account, t2.ftype, t2.fsafe, t2.work_time, t2.tender_times, t2.apr,t2.each_time,t2.bill_starttime,t2.bill_endtime,t2.style,t2.repayment_account,t2.repayment_yesaccount";
		}	
		
		//封装条件
		$_where = " where 1=1 ";
		if(isset($data['where']['borrow_id']) && $data['where']['borrow_id'] != ''){
			$_where .= " and t1.borrow_id = ".$data['where']['borrow_id'];
		}
		if(isset($data['where']['title']) && $data['where']['title'] != ''){
			$_where .= " and t2.title like '%".$data['where']['title']."%'";
		}
		if(isset($data['where']['fstatus']) && $data['where']['fstatus'] == 0){
			$_where .= " and t1.fstatus = 0";
		}elseif(isset($data['where']['fstatus']) && $data['where']['fstatus'] != -1){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['username']) && $data['where']['username'] != ''){
			$_where .= " and t3.username like '%".$data['where']['username']."%'";
		}
		if(isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		if($data['where']['fstatus'] == 0){
			if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
				$strtime = strtotime($data['where']['strtime'].' 00:00:00');
				$_where .= " and t1.repayment_time >= ".$strtime;
			}
			if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
				$endtime = strtotime($data['where']['endtime'].' 23:59:59');
				$_where .= " and t1.repayment_time <= ".$endtime;
			}
		}elseif($data['where']['fstatus'] == 1){
			if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
				$strtime = strtotime($data['where']['strtime'].' 00:00:00');
				$_where .= " and t1.repayment_yestime >= ".$strtime;
			}
			if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
				$endtime = strtotime($data['where']['endtime'].' 23:59:59');
				$_where .= " and t1.repayment_yestime <= ".$endtime;
			}
		}
		
		
		//排序
		$order  = " order by t1.repayment_time asc ";
		if(isset($data['order']) && $data['order'] == 'desc'){
			$order  = " order by t1.repayment_time desc ";
		}
		//封装sql
		if(isset($data['page_size'])){
			$page_size = $data['page_size'];	
		}
		if(isset($data['page_start'])){
			$page_start = $data['page_start'];	
		}
		$sql_result = "select $select from rsh_borrow_repayment as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id";
		$sql_result .= $_where;
		$sql_result .= $order;
		if(isset($data['page_size'])){
			$sql_result .= " limit $page_start, $page_size";	
		}
		$query = $this->db->query($sql_result);
		$data['repayment_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow_repayment as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['repayment_count'] = $query->row()->count;
		return $data;
	}
	
	function get_repayment_lz_borrow($user_id){
		$sql = "select id,title,time_limit,account_yes from rsh_borrow WHERE user_id={$user_id} AND ftype=4 AND fstatus=3 AND account_yes>0 ORDER BY id DESC";
		$query = $this->db->query($sql);
		return $query->result_array();
	}
	
	/**
	 * 根据标和期数获取马甲应收
	 * Enter description here ...
	 * @param unknown_type $data
	 */
	function get_borrow_collection_majia($data){
		$borrow_id 	= $data['borrow_id'];
		$forder		= $data['forder'];
		$fstatus = $data['fstatus'];
		
		if($fstatus != -1){
			$_where .= " and fstatus = ".$fstatus;
		}
		
		if($fstatus == 0){
			if(isset($data['strtime']) && $data['strtime'] != 0){
				$strtime = strtotime($data['strtime'].' 00:00:00');
				$_where .= " and repay_time >= ".$strtime;
			}
			if(isset($data['endtime']) && $data['endtime'] != 0){
				$endtime = strtotime($data['endtime'].' 23:59:59');
				$_where .= " and repay_time <= ".$endtime;
			}
		}elseif($fstatus == 1){
			if(isset($data['strtime']) && $data['strtime'] != 0){
				$strtime = strtotime($data['strtime'].' 00:00:00');
				$_where .= " and repay_yestime >= ".$strtime;
			}
			if(isset($data['endtime']) && $data['endtime'] != 0){
				$endtime = strtotime($data['endtime'].' 23:59:59');
				$_where .= " and repay_yestime <= ".$endtime;
			}
		}
		
		$sql = "select sum(repay_account) as total_repay_account from rsh_borrow_collection WHERE 
				forder={$forder} AND borrow_id={$borrow_id} {$_where} and user_id in (select user_id from rsh_user where is_self=1)";
		
		
		$query = $this->db->query($sql);
		$ret = $query->result_array();
		return $query->row()->total_repay_account;
	}

	/**
	 * 查看投标的信息
	 * @param Array $data
	 * @return Array
	 */
	function get_lz_repayment_list($data = array()){
		//封装查询内容
		$select = "*";
		if(isset($data['select']) && $data['select'] == 1){
			$select = " t1.id, t1.user_id, t1.fstatus, t1.forder, t1.borrow_id, t1.repay_time as repayment_time,
					    t1.repay_yestime as repayment_yestime,
						t1.repay_account as repayment_account, t1.repay_yesaccount as repayment_yesaccount, 
						t1.interest, t1.capital, t1.late_days, 
						t1.late_interest, t2.id as borrow_id, 
						t2.title, t2.ftype, t2.time_limit, t2.apr, t2.is_day, t2.time_limit_day ";
		}
		
		//封装条件
		$_where = " where 1=1 and t2.fstatus=3 and ftype=4 ";
		if(isset($data['where']['ftype']) && $data['where']['ftype'] != ''){
			$_where .= " and t2.ftype = ".$data['where']['ftype'];
		}
		if(isset($data['where']['borrow_id']) && $data['where']['borrow_id'] != ''){
			$_where .= " and t1.borrow_id = ".$data['where']['borrow_id'];
		}
		if($data['where']['fstatus'] != -1){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and t2.user_id = ".$data['where']['user_id'];
		}
		if($data['where']['fstatus'] == 0){
			if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
				$strtime = strtotime($data['where']['strtime'].' 00:00:00');
				$_where .= " and t1.repay_time >= ".$strtime;
			}
			if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
				$endtime = strtotime($data['where']['endtime'].' 23:59:59');
				$_where .= " and t1.repay_time <= ".$endtime;
			}
		}elseif($data['where']['fstatus'] === 1){
			if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
				$strtime = strtotime($data['where']['strtime'].' 00:00:00');
				$_where .= " and t1.repay_yestime >= ".$strtime;
			}
			if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
				$endtime = strtotime($data['where']['endtime'].' 23:59:59');
				$_where .= " and t1.repay_yestime <= ".$endtime;
			}
		}
		
		//排序
		$order  = " order by t1.id asc ";
		if(isset($data['order']) && $data['order'] == 'desc'){
			$order  = " order by t1.id desc ";
		}
		if(isset($data['order']) && $data['order'] == '1'){
			$order  = " order by t1.repay_time asc ";
		}
		//封装sql
		if(isset($data['page_size'])){
			$page_size = $data['page_size'];	
		}
		if(isset($data['page_start'])){
			$page_start = $data['page_start'];	
		}
		$sql_result = "select $select from rsh_borrow_collection as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id";
		$sql_result .= $_where;
		$sql_result .= $order;
		if(isset($data['page_size'])){
			$sql_result .= " limit $page_start, $page_size";	
		}
		$query = $this->db->query($sql_result);
		$data['repayment_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow_collection as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['repayment_count'] = $query->row()->count;
		return $data;
	}
	

	/**
	 * 流转标还款列表汇总
	 * @param Array $data
	 * @return Array
	 */
	function get_lz_repayment_huizong_list($data = array()){
		//封装查询内容
		$select = "*";
		if(isset($data['select']) && $data['select'] == 1){
			$select = "t1.id,t1.title,t1.time_limit,t2.forder,SUM(t2.repay_account) as repay_accounts,t2.repay_time ";
		}
	
		//封装条件
		$_where = " where 1=1 and t1.fstatus=3 and t1.ftype in(4,6) ";
		if($data['where']['fstatus'] != -1){
			$_where .= " and t2.fstatus = ".$data['where']['fstatus'];
		}
		if(isset($data['where']['title']) && $data['where']['title'] != '' ){
			$_where .= " and t1.title = '{$data['where']['title']}'";
		}
		if($data['where']['fstatus'] == 0){
			if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
				$strtime = strtotime($data['where']['strtime'].' 00:00:00');
				$_where .= " and t2.repay_time >= ".$strtime;
			}
			if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
				$endtime = strtotime($data['where']['endtime'].' 23:59:59');
				$_where .= " and t2.repay_time <= ".$endtime;
			}
			$order  = " order by t2.repay_time asc ";
		}elseif($data['where']['fstatus'] == 1){
			if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
				$strtime = strtotime($data['where']['strtime'].' 00:00:00');
				$_where .= " and t2.repay_yestime >= ".$strtime;
			}
			if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
				$endtime = strtotime($data['where']['endtime'].' 23:59:59');
				$_where .= " and t2.repay_yestime <= ".$endtime;
			}
			$order  = " order by t2.repay_yestime desc ";
		}
	
		//排序
		$group  = " GROUP BY t2.borrow_id "; 
		//$order  = " order by t2.repay_time asc ";
		
		
		
		//封装sql
		
		$sql_result = "select $select from rsh_borrow AS t1 LEFT JOIN rsh_borrow_collection AS t2 ON t1.id=t2.borrow_id";
		$sql_result .= $_where;
		$sql_result .= $group;
		$sql_result .= $order;
		
		if(isset($data['limit']) && $data['limit'] == 'all'){
			$query = $this->db->query($sql_result);
			$data['repayment_list'] = $query->result_array();
		}else{
			if(isset($data['page_size'])){
				$page_size = $data['page_size'];
			}
			if(isset($data['page_start'])){
				$page_start = $data['page_start'];
			}
			$sql_result .= " limit $page_start, $page_size";
			$query = $this->db->query($sql_result);
			$data['repayment_list'] = $query->result_array();
		}
		
		
	
		//总记录条数
		$sql_count = "select count(DISTINCT(t2.borrow_id)) as count from rsh_borrow AS t1 LEFT JOIN rsh_borrow_collection AS t2 ON t1.id=t2.borrow_id";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['repayment_count'] = $query->row()->count;
		//总还款金额
		$sql_sum = "select sum(t2.repay_account) as totalmoney from rsh_borrow AS t1 LEFT JOIN rsh_borrow_collection AS t2 ON t1.id=t2.borrow_id";
		$sql_sum .= $_where;
		$query = $this->db->query($sql_sum);
		$data['totalmoney'] = $query->row()->totalmoney;
		//真实还款金额
		$_where .= " and u.is_self=0 ";
		$sql_sum = "select sum(t2.repay_account) as realmoney from rsh_borrow AS t1 LEFT JOIN rsh_borrow_collection AS t2 ON t1.id=t2.borrow_id left join rsh_user as u on t2.user_id=u.user_id";
		$sql_sum .= $_where;
		$query = $this->db->query($sql_sum);
		$data['realmoney'] = $query->row()->realmoney;
		
		return $data;
	}
	
	/**
	 * 用户自动投标列表
	 * @param $data
	 */
	function get_borrow_auto_list($data){
		//封装查询内容
		$select = "*";
		if(isset($data['select']) && $data['select'] == 1){
			$select = " * ";
		}
		
		//封装条件
		$_where = " where is_del=0 ";
		if(isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		
		//排序
		$order  = " order by t1.id desc ";
		
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_auto as t1 ";
		$sql_result .= $_where;
		$sql_result .= $order;
		$query = $this->db->query($sql_result);
		$data['borrow_auto_list'] = $query->result_array();
		return $data;
	}
	
	/**
	 * 查询
	 * @param $data
	 */
	function get_borrow_auto_obj($id, $data = array()){
		$select = "*";
		$this->db->select($select);
		$this->db->where('id', $id);
		$this->db->where('user_id', $data['user_id']);
		$query = $this->db->get('rsh_borrow_auto');
		return $query->row_array();
	}
	
	/**
	 * 删除标
	 * @param $data
	 */
	function delete_borrow_auto($data = array()){
		$this->db->where($data);
		$this->db->update('rsh_borrow_auto', array('is_del'=>1));
		$key = 'auto_tender_count';
		$this->mycache->delete($key);
		return $this->db->affected_rows();
	}
	
	function update_borrow_auto($id, $data){
		$this->db->where('id', $id);
		$this->db->update('rsh_borrow_auto', $data);
		$key = 'auto_tender_count';
		$this->mycache->delete($key);
		return $this->db->affected_rows();
	}
	
	/**
	 * 自动投标
	 * @param $borrow_id
	 */
	function auto_tender_borrow($borrow_id){
		// 获取借款标的单独信息
		$borrow_result = self::get_borrow_obj($borrow_id);
		// 计算标的允许可自动投标总金额
		$_user_invest_money =  ($borrow_result['account'] * $borrow_result['auto_apr'] )/100;
		
		// TODO 待优化 ，计算每个VIP级别可自动投标金额
		$_investrank = " select id,round((investpercent/100 * {$_user_invest_money}),2) as money from rsh_invest_rank where fstatus = 0 ";
		$query = $this->db->query($_investrank);
		
		$rankid_pencent = $query->result_array();
		$vip_money = Array();
		foreach ( $rankid_pencent as $percent) {
			$vip_money[$percent['id']] = $percent['money'];
		}
		// 标的上线时间是否在有效时间范围内
		$now = time();
		$auto_sql = "SELECT t1.*,u.invest_rank_id as vip_id
					 FROM      	rsh_borrow_auto  t1
					 LEFT JOIN 	rsh_account      t2    ON 	t1.user_id = t2.user_id
					 LEFT JOIN 	rsh_user          u    ON 	t1.user_id = u.user_id
					 WHERE 	t1.fstatus=1  
					 AND   	t1.is_del=0
					 AND    t1.valid_start_time <{$now} AND t1.valid_end_time >{$now} 
					 AND   	t2.use_money >= {$borrow_result['lowest_account']} ";
		$auto_sql .= " GROUP BY t1.user_id  ORDER BY t1.add_time  ";
		$query = $this->db->query($auto_sql);
		$borrow_auto_list = $query->result_array();
		
		//echo $auto_sql;exit;
		foreach($borrow_auto_list as $borrow_auto){
			// 获取该VIP组级别的现有可投总金额
			$buseful_money = 0;
			$vip_id = 0;
			foreach ( $vip_money as $id => $money) {
				if($id == $borrow_auto['vip_id'] ){
					$buseful_money = $money;
					$vip_id = $id;
					break;
				}
			}
			
			//echo $buseful_money;exit;
			if($vip_id <= 0){//无VIP等级
				continue;
			}
			// 标的中VIP组级别可投金额 50 ，跳过此VIP级别的用户,限定，可投金额必须大于50 
			if($buseful_money <50 || $buseful_money <  $borrow_result['lowest_account'] ){
				continue;
			}
			// 不能投自己的标
			if($borrow_result['user_id'] == $borrow_auto['user_id']){
				continue;
			}
			
			$tender_account 	= 0;//下限
			$tender_account1 	= 0;//上限
			if($borrow_auto['tender_type'] == 1){//****** by liub 20141119 一点投标的
				$tender_account  = $borrow_auto['tender_account_min'];
				$tender_account1 = $borrow_auto['tender_account_max'];
			}
			// 标的中该VIP组级别用户可投金额 < 用户设置的最低金额
			if ( $buseful_money < $tender_account){
				continue;
			}
			
			if($borrow_auto['borrow_style_status'] == 1){
				if($borrow_auto['borrow_style'] != $borrow_result['style']){
					continue;//不符合还款方式要求
				}
			}
			
		
			
			if($borrow_auto['award_status'] == 1){
				if($borrow_auto['award_first'] > $borrow_result['funds'] || 
					$borrow_auto['award_last'] < $borrow_result['funds']){
					continue;//不符合奖励要求
				}
			}
			
			if($borrow_auto['apr_status'] == 1){
				if($borrow_auto['apr_first'] > $borrow_result['apr'] || 
					$borrow_auto['apr_last'] < $borrow_result['apr']){
					continue;//不符合利率要求
				}
			}
			
			if($borrow_auto['timelimit_status'] == 1){
				if($borrow_auto['timelimit_month_first'] > $borrow_result['time_limit'] || 
					$borrow_auto['timelimit_month_last'] < $borrow_result['time_limit']){
					continue;//不符合期限要求
				}
			}
		
			//$mode = substr(strval($borrow_auto['user_id']),-1,1);
			// 获取用户账户信息(可用余额)
			$this->load->model('Account_model');
			$user_account = $this->Account_model->get_account($borrow_auto['user_id']);
			///echo $user_account['use_money']."___".$tender_account;exit;
			if ($user_account['use_money'] < $tender_account){// 用户可用金额  < 设置最低金额
				continue;
			}
			
			
			if($tender_account > $tender_account1 && $tender_account1 !=0 ){// 设置最低金额 < 设置最高金额
				continue;
			}
			
			
			// 封装投标所需信息
			$data = Array();
			$data['id'] 			= $borrow_id;
			$data['ip'] 			= '127.0.0.1';
			$data['user_id'] 		= $borrow_auto['user_id'];
			$data['borrow_user_id'] = $borrow_result['user_id'];
			
			// ****** by liub 20141119 计算投标金额
			if($tender_account1 != $tender_account){// 自动投标最小金额 != 自动投标最大金额
				$min = 0;
				$max = 0;
				$mid = 0;
				if($borrow_auto['retain_money_status'] == 1){//保留金额
					$mid = $user_account['use_money'] - $borrow_auto['retain_money'];
				}else{
					$mid = $tender_account;
				}
				
				if($mid < $tender_account){ 
					continue;
				}elseif($mid >= $tender_account1 ){
					$max = $tender_account1;
					$min = $tender_account;
				}elseif($mid < $tender_account1 && $mid >= $tender_account ){
					$max = $tender_account1;
					$min = $mid;
				}
				// ****** 和VIP组别现在可投金额比较，取小值
				if($min > $buseful_money){
					continue;
				}
				if($max > $buseful_money ){
					$max = $buseful_money;
				}//------------end
				if($min < $borrow_result['lowest_account']){
					$min = $borrow_result['lowest_account'];
				}
				$min = ceil($min / 50 ) * 50;// 最小投标金额必须为 50 的倍数
				$base_num = round($max /$min,0);// 随机数最大值
				if($base_num == 0 ){
					continue;
				}
				$rand_num = rand(1,$base_num);// 随机数
				$tender_account = $rand_num * $min;// 投标金额 = 随机金额 = 随机数*最小投标金额（50的倍数）
				// 与自动投标设置中的最小最大金额比较
				if($tender_account <  $borrow_auto['tender_account_min'] || $tender_account >  $borrow_auto['tender_account_max'] ){
					continue;
				}
				// 与标的设置中的最小最大金额比较
				if($tender_account < $borrow_result['lowest_account'] || $tender_account > $buseful_money ){
					continue;
				}elseif($tender_account > $borrow_result['most_account'] && $borrow_result['most_account'] > 0){
					// ****** by liub 20141231 最大金额无限制，如果随机金额 大于标的单笔最大限额 ,直接取单笔金额最大值
					$tender_account = $borrow_result['most_account'];
				}
				/*
				if($tender_account %50 != 0){//检测投标金额必须为50的倍数
					continue;
				}
				*/
			
				//20150803 @zhu 
				if($tender_account < 50){//检测投标金额必须为50以上
					continue;
				}
				//投标金额
				$data['money'] 			= $tender_account;
				//实际金额
				$data['account'] 		= $tender_account;
			}else{
				
				// 自投规则中的 金额为定值
				if($borrow_auto['retain_money_status'] == 1){
					$tender_account =  $user_account['use_money'] - $borrow_auto['retain_money'];
				}
				
				// 与自动投标设置中的最小最大金额比较
				if($tender_account <  $borrow_auto['tender_account_min'] ){
					continue;
				}
				if($tender_account >=  $borrow_auto['tender_account_max'] ){
					$tender_account = $borrow_auto['tender_account_max'];
				}
				
				// 与标的设置中的最小最大金额比较
				if($tender_account < $borrow_result['lowest_account']){
					continue;
				}elseif($tender_account > $borrow_result['most_account'] && $borrow_result['most_account'] > 0){
					// ****** by liub 20141231 最大金额无限制，如果随机金额 大于标的单笔最大限额 ,直接跳过
					continue;
				}
				
				if($tender_account > $buseful_money){
					continue;
				}
				// eg:定标金额必须为50的倍数，否则无法投标
				/*
				if($tender_account %50 != 0){
					continue;
				}
				*/
				//20150803 @zhu 
				if($tender_account < 50){//检测投标金额必须为50以上
					continue;
				}
				//投标金额
				$data['money'] 			= $tender_account;
				//实际金额
				$data['account'] 		= $tender_account;
			}
			// 防止同步问题且防止随机金额<标的单笔最小投资金额---start
			$tender_acc = floor($data['money']/$borrow_result['lowest_account']);
			if ($tender_acc<1){
				continue;
			}
			$data['account'] 	= $tender_acc * $borrow_result['lowest_account'];
			if($user_account['use_money']<$data['account']){
				continue;
			}//---end
			// 更新‘设置自动投标’中 信息
			$auto_data['tender_count']=intval($borrow_auto['tender_count']+1);
			$auto_data['last_tender_time']=time();
			// 投标
			if($borrow_result['ftype'] == 1){// !@#$%标的
				// 投标,自动投标不激活代金卷
				
				//
				
				$falg = self::borrow_tender($data);	
				
				//echo $falg."_00000";exit;
				if(1 == $falg){
					// 现VIP组级别用户可投金额 - 此次投递金额 = 之后VIP组级别用户可投金额
					$vip_money[$vip_id] = $buseful_money - $data['money'];
					// 更新自动投标次数和最新时间
					$this->update_borrow_auto($borrow_auto['id'],$auto_data);
				}
			}else{// TODO 其他标种
				//echo "kkkkooooooooo1";exit;
			}
		}
	}
	
	function index_total($type = 0){
		$mkey = "index_total_".$type;
		//$this->mycache->delete($mkey);
		$ret = $this->mycache->get_array($mkey);
		if($ret != false){
			return $ret;
		}
		if($type == 0){//月排行
			$date = date("Y-m-d");
			$firstday = date("Y-m-01",strtotime($date));
			$lastday = date("Y-m-d",strtotime("$firstday +1 month"));
			$start = strtotime($firstday);
			$end = strtotime($lastday)-1;	
		}elseif ($type==2){//昨日排行
			$today = date('Y-m-d');
			$start = strtotime($today)-(3600*24);
			$end = strtotime($today);
		}else{//日排行
			$today = date('Y-m-d');
			$start = strtotime($today);
			$end = time();
		}
		/*
		$sql = "select sum(t1.account) as money,t2.username from rsh_borrow_tender t1 left join 
				rsh_user t2 on t1.user_id=t2.user_id
				left join rsh_borrow t3 on t1.borrow_id=t3.id 
				where t1.add_time>$start and t1.add_time<$end AND t3.ftype!=5 and t3.is_day=0
				GROUP BY t1.user_id ORDER BY money DESC,t1.add_time ASC LIMIT 10";
		*/
		if($type == 5){
			$sql = "select sum(t1.account) as money,t2.username from rsh_borrow_tender t1 left join 
				rsh_user t2 on t1.user_id=t2.user_id
				left join rsh_borrow t3 on t1.borrow_id=t3.id 
				where t3.ftype=1 
				GROUP BY t1.user_id ORDER BY money DESC,t1.add_time ASC LIMIT 12";
		}else if ($type==2){
			$sql = "select sum(t1.account) as money,t2.username from rsh_borrow_tender t1 left join 
				rsh_user t2 on t1.user_id=t2.user_id
				left join rsh_borrow t3 on t1.borrow_id=t3.id 
				where t1.add_time>$start and t1.add_time<$end AND t3.ftype=1
				GROUP BY t1.user_id having(sum(t1.account)>=50000) ORDER BY money DESC,t1.add_time ASC LIMIT 10 ";
		}else{
			$sql = "select sum(t1.account) as money,t2.username from rsh_borrow_tender t1 left join 
				rsh_user t2 on t1.user_id=t2.user_id
				left join rsh_borrow t3 on t1.borrow_id=t3.id 
				where t1.add_time>$start and t1.add_time<$end AND t3.ftype=1 
				GROUP BY t1.user_id ORDER BY money DESC,t1.add_time ASC LIMIT 10";
		}
		
		$query = $this->db->query($sql);
		$ret = $query->result_array();
		$this->mycache->set_array($mkey,$ret, 180);
		return $ret;
	}
	
	
	//by liub 20150102 回款明细查询
	function get_user_collection($data = array()){
		//封装查询内容
		$select = "*";
		if($data['select'] == 1){
			$select = " t1.id, t1.fstatus, t1.forder, t1.borrow_id, t1.repay_time,t1.repay_yestime,
						t1.repay_account,t1.repay_yesaccount, t1.interest, t1.interest,t1.work_interest, t1.capital, t1.late_days, t1.late_interest, t1.tender_id, 
						t1.add_time, t2.id as borrow_id, 
						t2.title, t2.account, t2.apr, t2.ftype, t2.time_limit, t2.is_day, t2.time_limit_day,t2.style ";
		}
		
		//封装条件
		if(isset($data['where']['fstatus']) && $data['where']['fstatus']==0){
			$_where = " where t2.fstatus=3 and t3.transfer_status<2 ";
		}else{
			$_where = " where t2.fstatus=3 ";
		}
		//$_where = " where t2.fstatus=3 and t3.transfer_status<2 ";
		if(isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		if(isset($data['where']['fstatus'])){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}
		if($data['type']==3){// 代收
			if (isset($data['where']['strtime']) && $data['where']['strtime']!=''){
				$strtime = strtotime($data['where']['strtime']);
				$_where .= " and t1.repay_time >= ".$strtime;
			}
			if (isset($data['where']['endtime']) && $data['where']['endtime']!=''){
				$endtime = strtotime($data['where']['endtime'])+3600*24;
				$_where .= " and t1.repay_time < ".$endtime;
			}
		
		}elseif($data['type']==4){//已收
			if (isset($data['where']['strtime']) && $data['where']['strtime']!=''){
				$strtime = strtotime($data['where']['strtime']);
				$_where .= " and t1.repay_yestime >= ".$strtime;
			}
			if (isset($data['where']['endtime']) && $data['where']['endtime']!=''){
				$endtime = strtotime($data['where']['endtime'])+3600*24;
				$_where .= " and t1.repay_yestime < ".$endtime;
			}
		}else{
			if (isset($data['where']['strtime']) && $data['where']['strtime']!=''){
				$strtime = strtotime($data['where']['strtime']);
				$_where .= " and t1.repay_yestime >= ".$strtime;
			}
			if (isset($data['where']['endtime']) && $data['where']['endtime']!=''){
				$endtime = strtotime($data['where']['endtime'])+3600*24;
				$_where .= " and t1.repay_yestime < ".$endtime;
			}
		}

		
		//排序
		$order  = " order by t1.id asc ";
		if(isset($data['order']) && $data['order'] == 1){
			$order  = " order by t1.repay_time asc ";
		}elseif(isset($data['order']) && $data['order'] == 2){
			$order  = " order by t2.id asc ";
		}elseif(isset($data['order']) && $data['order'] == 3){
			$order  = " order by t1.id desc ";
		}elseif(isset($data['order']) && $data['order'] == 4){
			$order  = " order by t1.fstatus asc, t1.repay_yestime desc,t1.borrow_id desc";
		}
		
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		$sql_result = "select $select from rsh_borrow_collection as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id left join rsh_borrow_tender as t3 on t1.tender_id=t3.id ";
		$sql_result .= $_where;
		$sql_result .= $order;
		
		//echo $sql_result;exit;
		if (isset($data['limit']) && $data['limit']=='all'){
			$query = $this->db->query($sql_result);
			return $query->result_array();
		}else{
			$sql_result .= " limit $page_start, $page_size";
			$query = $this->db->query($sql_result);
			if(isset($data['list']) && $data['list'] == 1){
				return $query->result_array();
			}
			$data['collection_list'] = $query->result_array();
			
			//总记录条数
			$sql_count = "select count(*) as count from rsh_borrow_collection as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id left join rsh_borrow_tender as t3 on t1.tender_id=t3.id ";
			$sql_count .= $_where;
			$query = $this->db->query($sql_count);
			$data['collection_count'] = $query->row()->count;
			return $data;	
		}
		/*
		$query = $this->db->query($sql_result);
		if(isset($data['list']) && $data['list'] == 1){
			return $query->result_array();
		}
		$data['collection_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow_collection as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id ";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['collection_count'] = $query->row()->count;
		return $data;	
		*/	
	}
	
	
	function get_user_borrow($data){
		//封装查询内容
		$select = "*";
		if($data['select'] == 1){
			$select = " t1.id, t1.user_id, t1.title, t1.account , t1.apr, t1.funds, t1.time_limit , t1.style,
						t1.fstatus, t1.ftype, t1.award, t1.is_day, t1.time_limit_day, t1.verify_time, t1.account_yes,
						t1.valid_time, t1.end_time, t1.repayment_time, t1.repayment_account,t1.repayment_yesaccount, t1.add_time ";
		}
		
		//封装条件
		$_where = " where 1=1 ";
		if(isset($data['where']['user_id']) && $data['where']['user_id'] >0){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		if($data['where']['fstatus'] === 0){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}elseif(isset($data['where']['fstatus']) && $data['where']['fstatus'] != ''){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}else{
			$_where .= " and (t1.fstatus = 1 or t1.fstatus = 3)";
		}
		if(isset($data['where']['fstatus1']) && $data['where']['fstatus1'] == 'over'){
			$_where .= " and t1.repayment_account<=t1.repayment_yesaccount ";
		}elseif(isset($data['where']['fstatus1']) && $data['where']['fstatus1'] != ''){
			$_where .= " and t1.repayment_account = t1.repayment_yesaccount ";
		}
		
		//排序
		$_order  = " order by t1.id desc ";
		
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		$sql_result = "select $select from rsh_borrow as t1 ";
		$sql_result .= $_where;
		$sql_result .= $_order;
		$sql_result .= " limit $page_start, $page_size";
		$query = $this->db->query($sql_result);
		$data['borrow_list'] = $query->result_array();
		
		//总记录条数
		$sql_count = "select count(*) as count from rsh_borrow as t1 ";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['borrow_count'] = $query->row()->count;
		return $data;
	}	
	
	
	//TODO 20141128 by liub  撤标流程待确认
	/**
	 * 撤标
	 * @param $data
	 */
	function Cancel($data = array()){
		$borrow_id  = $data['id'];
		$user_id    = $data['user_id'];
		$ip   		= $data['ip'];
		$this->db->select("id,title,fstatus,apr,account,ftype");
		$this->db->where(array('id'=>$borrow_id,'user_id'=>$user_id));
		$query = $this->db->get('rsh_borrow');
		$borrow_obj_result = $query->row_array();
		$this->load->model('Account_model');
        $status1 = $borrow_obj_result['fstatus'];
        
        // 已上线，不允许撤回
		//if(($status1 == 0) || ($status1 == 1)){
        if(($status1 == 0)){	
        	/*tangc 死锁问题*/
			$this->db->trans_strict(FALSE);
		    $this->db->trans_begin();
        	// 修改
			//$this->db->query("update rsh_borrow set fstatus=5 where id=$borrow_id and user_id=$user_id");
			$this->db->query("update rsh_borrow set is_verify = 0,is_check = 0 where id=$borrow_id and user_id=$user_id");
			//$mode = substr(strval($user_id),-1,1);
			// 20141128 by liub 
			/*
			if($borrow_obj_result['ftype'] == 5){//秒标解冻
				$user_account = $this->Account_model->get_account($user_id);
				$log['user_id'] 		= $user_account['user_id'];
				$log['ftype'] 			= BORROW_FROST;//解冻
				$log['money'] 			= $borrow_obj_result['account'] * $borrow_obj_result['apr'] /(100*12);
				$log['total'] 			= $user_account['total'];
				$log['use_money'] 		= $user_account['use_money']+$log['money'];
				$log['no_use_money'] 	= $user_account['no_use_money']-$log['money'];
				$log['collection'] 		= $user_account['collection'];
				$log['to_user'] 		= 1;
				$log['remark'] 			= "对[<a href='/borrow/obj/{$borrow_id}.html' target=_blank>{$borrow_obj_result['title']}</a>]借款的解冻";
				$log['add_time'] 		= time();
				$log['addip'] 			= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$user_id};");
			}
			*/
			
			//20141128 by liub  修改，拒绝撤回!.......返回所有投资者的金钱。
			/*
			$query = $this->db->query("select id,account,borrow_id,user_id from rsh_borrow_tender where borrow_id={$borrow_id}");
			$tender_list = $query->result_array();
			foreach ($tender_list as $tender){
				$mode = $tender['user_id']%100;
				$user_account = $this->Account_model->get_account($tender['user_id']);
				$log['user_id'] 		= $user_account['user_id'];
				$log['ftype'] 			= INVEST_FALSE;//扣除冻结款
				$log['money'] 			= $tender['account'];
				$log['total'] 			= $user_account['total'];
				$log['use_money'] 		= $user_account['use_money']+$log['money'];
				$log['no_use_money'] 	= $user_account['no_use_money']-$log['money'];
				$log['collection'] 		= $user_account['collection'];
				$log['to_user'] 		= $user_id;
				$log['remark'] 			= "招标[<a href='/borrow/obj/{$borrow_id}.html' target=_blank>{$borrow_obj_result['title']}</a>]失败返回的投标额";
				$log['add_time'] 		= time();
				$log['addip'] 			= $ip;
				
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tender['user_id']}");
				$this->db->query("update rsh_borrow_collection set fstatus=2 where tender_id={$tender['id']}");
				$this->db->query("update rsh_borrow_tender set fstatus=2 where id={$tender['id']}");
			}
			*/
			if ($this->db->trans_status() === TRUE) {
		        $this->db->trans_commit();
		        return 1;
		    } else {
		        $this->db->trans_rollback();
		        //@todo 异常处理部分
		        return 0;
		    }
		}else{
			return 0;
		}
	}
	
	private function queryBFAccount($user_id,$need_repay_account){
		$flag = true;
		$user_account = $this->Account_model->get_account($user_id);
		if ($user_account['use_money'] < $need_repay_account){
			$flag = false;
		}
		$balance_arr = self::queryBalance($user_id);
		$balance = 0;
		$flag_msg = null;
		if($balance_arr['code'] == 'CSD000'){
			$balance  = $balance_arr['balance'];
		}else{
			$flag_msg =  "还款失败,".$balance_arr['msg'];
			// ****** TODO 机制：还款因查询余额失败，手工重新再次还款。
			return 2;
		}
		if($balance == -1){
			$flag_msg =  "还款失败，请稍候再试";
			return 3;
		}
		if($balance - $user_account['use_money'] < 0){
			$flag_msg =  "您的宝付账户余额 < 平台账户余额，请联系客服";
			// ****** TODO 机制：还款因查询余额失败，手工重新再次还款。
			return 4;
		}
		if( $balance - $need_repay_account < 0 ){
			$flag_msg =  "您的宝付账户余额<本期应还总金额，请联系客服";
			// ****** TODO 机制：还款因查询余额失败，手工重新再次还款。
			$flag = false;
		}
		
		return $flag;
	}
	
	/****** 20141227 by liub  资金托管，还款
	 * 还款
	 * @param $data
	 */
	function repay($data = array()){
		$repayment_id  	= $data['repayment_id'];
		$ip				= $data['ip'];
		$this->load->model('Account_model');
		$this->load->model('User_model');
		$this->load->model('Message_model');
		$this->load->model('Credit_model');
		
		$sql = "select  p1.id,p1.borrow_id,p1.forder,p1.fstatus,p1.user_id,p1.repayment_time,
						p1.repayment_account,p1.interest,p1.capital,p1.late_interest,p1.late_days,
						p2.title,p2.apr,p2.ftype,p2.style,p2.time_limit,p2.forst_account,p2.account,
						p2.loan_userid,p2.late_days as brw_latedays,p2.success_time,p2.late_apr 
						from rsh_borrow_repayment as p1 
						left join rsh_borrow as p2 on p1.borrow_id=p2.id 
						where (p1.fstatus=0 or p1.fstatus=2) 
						and p1.id={$repayment_id}";
		$query = $this->db->query($sql);
		$repayment_obj_result = $query->row_array();
		$user_id 	= $repayment_obj_result['user_id'];//还款者
		$borw_id 	= $repayment_obj_result['borrow_id'];//借款标的号
		$ftype 		= $repayment_obj_result['ftype'];//标的类型
		$this->load->model('Account_model');
		
		if ($repayment_obj_result == false){
			return "操作有误";
		}
		if ($repayment_obj_result['fstatus'] == 1){
			return "此标已经还款，请勿重复操作";
		}
		if ($repayment_obj_result['forder'] != 0){//判断上一期是否已还
			$_order = $repayment_obj_result['forder']-1;
			$sql_repay = "select fstatus from rsh_borrow_repayment where forder={$_order} and borrow_id={$repayment_obj_result['borrow_id']}";
			$query = $this->db->query($sql_repay);
			$result_repay = $query->row_array();
			if ($result_repay != false && $result_repay['fstatus'] != 1){
				return "你上期的借款还没还，请先还上期的";
			}
		}
		$flag = true;
		$need_repay_account = $repayment_obj_result['repayment_account'] + $repayment_obj_result['late_interest'];
		$user_account = $this->Account_model->get_account($user_id);
		if ($user_account['use_money'] < $need_repay_account){
			$flag = false;
		}
		// ****** begin 开始逾期判断
		if( 1 == $ftype ){//标的不计算逾期利息 
			if( !$flag ){
				return ;
			}
		}else{			
			$late_days = $repayment_obj_result['late_days'];// 目前已逾期天数
			$separate_days = (time()-$repayment_obj_result['repayment_time'])/(86400);// 至此次逾期间隔天数
			$brw_latedays = $repayment_obj_result['brw_latedays'];// 标的自定义允许逾期天数
			if($late_days < $brw_latedays ){// 判读是否需要调用 垫资账户进行垫资
				if(!$flag ){ // 借款者资金不足
					if(	 $separate_days >= $late_days   ){//红本
						self::culLateInterrest($repayment_obj_result);// 更新逾期天数
						return;
					}else{
						return;
					}
				}else{// 借款者资金足够
					
				}
			}else{
				$user_id = $repayment_obj_result['loan_userid'];
				// TODO 验证 还款中宝付账户余额是否足够
			}
		}
		// ****** end 
		// ****** 正常还款
		// 还款者账户余额 >= 还款本金+利息+逾期总利息
		$query = $this->db->query("select p1.user_id,p1.repay_account,p1.interest,p1.late_interest,
			p1.work_interest,p1.tender_id from rsh_borrow_collection as p1 
			left join  rsh_borrow_tender as p2 on p1.tender_id = p2.id  
			where p1.forder={$repayment_obj_result['forder']} and p1.fstatus !=3 and p2.borrow_id={$repayment_obj_result['borrow_id']}");
		$collection_list = $query->result_array();
		$sum_repaymoney = 0;
		foreach ($collection_list as $coll){
			// ****** by liub  20141228 还款信息统计
			// 投资者
			// by liub 20150205 还款金额 = 本金+利息+逾期利息
			$repay_total = $coll['repay_account']+$coll['late_interest'];
			$sum_repaymoney += $repay_total;
		}
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
		$mode = substr(strval($user_id),-1,1);
		$log = Array();
		$user_account = $this->Account_model->get_account($user_id);
		unset($log);
		$log['user_id'] 		= $user_account['user_id'];
		$log['ftype'] 			= REPAYMENT;//
		$log['money'] 			= $sum_repaymoney;//TODO by liub 20150205 修改总还金额
		$log['total'] 			= $user_account['total']-$log['money'];
		$log['use_money'] 		= $user_account['use_money']-$log['money'];
		$log['no_use_money'] 	= $user_account['no_use_money'];
		$log['collection'] 		= $user_account['collection'];
		$log['to_user'] 		= 1;
		$log['op'] 		= 1;
		$log['remark'] 			= "对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]还款";
		$log['add_time'] 		= time();
		$log['addip'] 			= $ip;
		$this->db->insert('rsh_account_log_'.$mode, $log);
		$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$user_id};");
		
		$query = $this->db->query("select p1.id, p1.user_id,p1.repay_account,p1.interest,p1.late_interest,
			p1.work_interest,p1.tender_id from rsh_borrow_collection as p1 
			left join  rsh_borrow_tender as p2 on p1.tender_id = p2.id 
			where p1.forder={$repayment_obj_result['forder']} and p1.fstatus !=3 and p2.borrow_id={$repayment_obj_result['borrow_id']}");
		$collection_list = $query->result_array();
		
		// 开始到期还款
		foreach ($collection_list as $coll){
			$reapy_coll_total = $coll['repay_account']+$coll['late_interest'];
			$mode = substr(strval( $coll['user_id']),-1,1);
			//更新投资人的分期信息
			$this->db->query("update rsh_borrow_collection set repay_yestime='".time()."',
				repay_yesaccount = {$reapy_coll_total} ,fstatus=1 where id={$coll['id']}");
			
			//更新投资的信息
			//****** by liub 20150103 返款时减掉 即时计息的利息
			$this->db->query("update rsh_borrow_tender set repayment_yesaccount=repayment_yesaccount+{$reapy_coll_total},
				wait_account=wait_account-{$reapy_coll_total},wait_interest=wait_interest-{$coll['interest']}-{$coll['work_interest']}-{$coll['late_interest']},
				repayment_yesinterest=repayment_yesinterest+{$coll['interest']}+{$coll['work_interest']}+{$coll['late_interest']} where id={$coll['tender_id']}");
			// ------ end
			unset($user_account);
			unset($log);
			$user_account = $this->Account_model->get_account($coll['user_id']);
			$log['user_id'] 		= $user_account['user_id'];
			$log['ftype'] 			= INVEST_REPAYMENT;
			$log['money'] 			= $reapy_coll_total;
			$log['total'] 			= $user_account['total'];
			$log['use_money'] 		= $user_account['use_money']+$log['money'];
			$log['no_use_money'] 	= $user_account['no_use_money'];
			$log['collection'] 		= $user_account['collection']-$log['money'];
			$log['to_user'] 		= $user_id;
			$log['remark'] 			= "客户对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]借款的还款";
			$log['add_time'] 		= time();
			$log['addip'] 			= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set use_money=use_money+{$log['money']},
				collection=collection-{$log['money']} where user_id={$coll['user_id']};");
		
		}

		//添加最后的还款金额
		$this->db->query("update rsh_borrow set repayment_yesaccount=repayment_yesaccount+{$sum_repaymoney} where id={$repayment_obj_result['borrow_id']}");
		//更新还款标的状态
		$this->db->query("update rsh_borrow_repayment set fstatus=1,
			repayment_yesaccount={$sum_repaymoney},repayment_yestime=".time()." where id=$repayment_id");
		
		if ($this->db->trans_status() === TRUE) {
        	$this->db->trans_commit();
        	return 1;
   		 } else {
        	$this->db->trans_rollback();
       	 	return "还款失败";
   	 	 }
	}
	
	
	/**
	 * 查询余额(服务端接口)
	 */
	private function queryBalance($user_id){
		$config['user_id'] 		= null;
		$this->load->library('baofooSdk/dto/request/BalanceDto',$config,'balanceDto');
		$this->load->library('baofooSdk/BaofooRequestService',0,'br_recharge');
		// 赋值
		$this->balanceDto->__set("user_id",$user_id);
		return $this->br_recharge->api_AccountBalance($this->balanceDto);
	}
	
	/***
	 * 
	 * 计算逾期利息
	 * */
	private function culLateInterrest($repayment_obj_result){
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
		// 计算逾期利息和逾期天数
		$yuqi_apr = $repayment_obj_result['late_apr'];//逾期日利率计算
		$late_interest = round((($repayment_obj_result['repayment_account'] + $repayment_obj_result['late_interest'] )* $yuqi_apr),2);
		// 更新 repayment 
		$repayment_update = "update rsh_borrow_repayment  set late_days = late_days+1 ,
			late_interest = late_interest + {$late_interest} where id = {$repayment_obj_result['id']}";
		
		$this->db->query($repayment_update);
		
		// 更新 collection,tender,account
		$query = $this->db->query("select p1.id as coll_id,p1.user_id,p1.repay_account,p1.interest,p1.late_interest,p1.capital,
			p1.work_interest,p1.tender_id from rsh_borrow_collection as p1 
			left join  rsh_borrow_tender as p2 on p1.tender_id = p2.id  
			where p1.forder={$repayment_obj_result['forder']} and p1.fstatus !=3 and p2.borrow_id={$repayment_obj_result['borrow_id']}");
		$collection_list = $query->result_array();
		
		// 开始到期还款
		foreach ($collection_list as $coll){
			$mode = substr(strval( $coll['user_id']),-1,1);
			//更新投资人的分期信息
			$late_interest_coll = round((($coll['repay_account']+$coll['late_interest']) * $yuqi_apr),2);
			$_coll_update = "update rsh_borrow_collection set late_days = late_days+1,late_interest = late_interest + {$late_interest_coll}
				 	where id={$coll['coll_id']}";
			$this->db->query($_coll_update);
			
			//更新投资的信息
			$this->db->query("update rsh_borrow_tender set 
					wait_account = wait_account + {$late_interest_coll}, wait_interest = wait_interest + {$late_interest_coll}
					where id={$coll['tender_id']}");
			// ------ end
			$user_account = $this->Account_model->get_account($coll['user_id']);
			$log['user_id'] 		= $user_account['user_id'];
			$log['ftype'] 			= LATE_COLLECTION;
			$log['money'] 			= $late_interest_coll;
			$log['total'] 			= $user_account['total']+$log['money'];
			$log['use_money'] 		= $user_account['use_money'];
			$log['no_use_money'] 	= $user_account['no_use_money'];
			$log['collection'] 		= $user_account['collection']+$log['money'];
			$log['to_user'] 		= $coll['user_id'];
			$log['remark'] 			= "客户对[<a href='/borrow/obj/{$repayment_obj_result['borrow_id']}.html' target=_blank>{$repayment_obj_result['title']}</a>]逾期的利息的收入";
			$log['add_time'] 		= time();
			$log['addip'] 			= "127.0.0.1";
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set total = total+{$log['money']},collection = collection+{$log['money']} where user_id={$coll['user_id']};");
		}
		
		if ($this->db->trans_status() === TRUE) {
        	$this->db->trans_commit();
        	return 1;
   		 } else {
        	$this->db->trans_rollback();
       	 	return "还款失败";
   	 	 }
	}
	
	
	/**
	 * 即时起息还款
	 * @param Array $data
	 * @return Array
	 */
	function lz_repay($data = array()){
		$id = $data['collection_id'];
		$ip = $data['ip'];
		$this->load->model('Account_model');
		$this->load->model('User_model');
		$this->load->model('Message_model');
		$this->load->model('Credit_model');
		
		$yestoday 	= strtotime(date('Y-m-d'));
		$nextday 	= strtotime(date('Y-m-d 23:59:59'));
		
		$query = $this->db->query("SELECT count(*) as count FROM rsh_borrow_collection
									WHERE repay_time>=$yestoday AND repay_time<=$nextday AND 
									fstatus=0 and id=$id ");
		$result_count = $query->row_array();
		
		$query = $this->db->query(" select p1.user_id,p1.id,p1.fstatus,p1.forder,p1.tender_id,p1.repay_time,p1.repay_yestime,
									p1.repay_account,p1.repay_yesaccount,p1.interest,p1.capital,p1.late_days,
									p1.interest,p1.add_time,p2.borrow_id,p2.account,p3.user_id as borrow_userid,
									p3.time_limit,p3.title,p3.style
									from rsh_borrow_collection as p1 left join rsh_borrow_tender as p2 
									on p1.tender_id=p2.id left join rsh_borrow as p3 on p2.borrow_id=p3.id 
									where p1.id=$id");
		
		$borrow_repayment_result = $query->row_array();
		$borrow_id 				 = $borrow_repayment_result["borrow_id"];
		$success_time 			 = $borrow_repayment_result["add_time"];
		$borrow_userid 			 = $borrow_repayment_result["borrow_userid"];
	
		if ($borrow_repayment_result['fstatus'] == 1){
			return "此借款已经还款，请不要乱操作";
		}
		
		//判断上一期是否已还
		if ($borrow_repayment_result['forder'] != 0){
			$_order = $borrow_repayment_result['forder'] - 1;
			$query_repay  = $this->db->query("select fstatus from rsh_borrow_collection where forder=$_order and borrow_id={$borrow_id}");
			$result_repay = $query_repay->row_array();
			if ($result_repay != false && $result_repay['fstatus'] != 1){
				return "你上期的借款还没还，请先还上期的";
			}
		}
		if($borrow_repayment_result['capital'] > 0){
			$late_result = late_interest($borrow_repayment_result['repay_time'], $borrow_repayment_result['capital']);
		}else{
			$late_result = late_interest($borrow_repayment_result['repay_time'], $borrow_repayment_result['interest']);
		}
		
		
		//判断可用余额是否够还款
		$user_account = $this->Account_model->get_account($borrow_userid);
		if ($user_account['use_money'] < $borrow_repayment_result['repay_account']+$late_result['late_interest']){
			return "账户余额不足，请充值。";
		}
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
   	 	$this->db->trans_begin();
		//扣除可用余额还款部分
		$bmode = substr(strval($borrow_userid),-1,1);
		$user_account = $this->Account_model->get_account($borrow_userid);
		$log['user_id'] 		= $borrow_userid;
		$log['ftype'] 			= REPAYMENT;
		$log['money'] 			= $borrow_repayment_result['repay_account'];
		$log['total'] 			= $user_account['total']-$log['money'];
		$log['use_money'] 		= $user_account['use_money']-$log['money'];
		$log['no_use_money'] 	= $user_account['no_use_money'];
		$log['collection'] 		= $user_account['collection'];
		$log['to_user'] 		= "0";
		$log['op'] 		= 1;
		$log['remark'] 			= "对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]还款";
		$log['add_time'] 	= time();
		$log['addip'] 		= $ip;
		$this->db->insert('rsh_account_log_'.$bmode, $log);
		$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow_userid}");
			
		$_repay_time = $borrow_repayment_result['repay_time']; 
		$re_time = (strtotime(date("Y-m-d",$_repay_time))-strtotime(date("Y-m-d",time())))/(60*60*24);
		
		$_repay_time = $borrow_repayment_result['repay_time']; 
		$re_time = (strtotime(date("Y-m-d",$_repay_time))-strtotime(date("Y-m-d",time())))/(60*60*24);
					
		$_order = $borrow_repayment_result['forder'];
		
		//如果网站已经待还，就不用还
		if ($borrow_repayment_result['fstatus']!=2){
			$query = $this->db->query("select p1.*,p2.user_id,p2.transfer_status from rsh_borrow_collection as p1 left join rsh_borrow_tender as p2 on p1.tender_id = p2.id where p1.forder='{$_order}' and p1.id='{$borrow_repayment_result['id']}'");
			$result = $query->result_array();
			foreach ($result as $key => $value){
				//更新投资人的分期信息
				$this->db->query("update rsh_borrow_collection set repay_yestime='".time()."',repay_yesaccount = repay_account,fstatus=1 where id = '{$value['id']}'");
				
				//更新投资的信息
				$interest_tmp = round($value['interest'], 2);
				$this->db->query(" update rsh_borrow_tender set repayment_yesaccount=repayment_yesaccount+{$value['repay_account']},
									wait_account=wait_account-{$value['repay_account']},wait_interest=wait_interest-{$interest_tmp},
									repayment_yesinterest=repayment_yesinterest+{$value['interest']} where id='{$value['tender_id']}'");
				
				// 返款投资者
				$umode = substr(strval($value['user_id']),-1,1);
				$user_account = $this->Account_model->get_account($value['user_id']);
				$log['user_id'] 		= $value['user_id'];
				$log['ftype'] 			= INVEST_REPAYMENT;
				$log['money'] 			= $value['repay_account'];
				$log['total'] 			= $user_account['total'];
				$log['use_money'] 		= $user_account['use_money']+$log['money'];
				$log['no_use_money'] 	= $user_account['no_use_money'];
				$log['collection'] 		= $user_account['collection']-$log['money'];
				$log['to_user'] 		= $borrow_userid;
				$log['remark'] 			= "客户对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款";
				$log['add_time'] 		= time();
				$log['addip'] 			= $ip;
				$this->db->insert('rsh_account_log_'.$umode, $log);
				$this->db->query("update rsh_account set use_money=use_money+{$log['money']},collection=collection-{$log['money']} where user_id={$value['user_id']}");
				
				//提醒设置
				$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$borrow_repayment_result['user_id'],
										'name'=>"客户对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"客户在".date("Y-m-d H:i:s")."对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款,还款金额为{$value['repay_account']}",
										'add_time'=>time(),'addip'=>$ip));
			}
		}
		
		//逾期还款
		if ($late_result['late_days'] > 0){
			$user_account = $this->Account_model->get_account($borrow_userid);
			$mode = substr(strval($borrow_userid),-1,1);
			$log['user_id'] 		= $borrow_userid;
			$log['ftype'] 			= LATE_REPAYMENT;
			$log['money'] 			= $late_result['late_interest'];
			$log['total'] 			= $user_account['total']-$log['money'];
			$log['use_money'] 		= $user_account['use_money']-$log['money'];
			$log['no_use_money'] 	= $user_account['no_use_money'];
			$log['collection'] 		= $user_account['collection'];
			$log['to_user'] 		= 1;
			$log['op'] 		= 1;
			$log['remark'] 			= "对[<a href='/borrow/obj{$borrow_repayment_result['borrow_id']}.html target=_blank>{$borrow_repayment_result['title']}</a>]借款的逾期金额的扣除";
			$log['add_time'] 		= time();
			$log['addip'] 			= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow_userid}");
				
			//更新逾期的信息
			$this->db->query("update rsh_borrow_repayment set late_days='{$late_result['late_days']}',late_interest='{$late_result['late_interest']}' where id = {$id}");
			
			unset($user_account);
		    unset($log);
		    	
		    if ($late_result['late_days'] <= 30){
		    	
				$this->db->query("select p1.*,p2.user_id from rsh_borrow_collection as p1 left join rsh_borrow_tender as p2 on 
								  p1.tender_id=p2.id where p1.id=$id");
				$result 	= $query->row_array();
				$mode = substr(strval($result['user_id']),-1,1);
				//更新投资的信息
				
				$user_account = $this->Account_model->get_account($result['user_id']);
				$log['user_id'] 		= $result['user_id'];
				$log['ftype'] 			= LATE_COLLECTION;
				if($result['capital'] > 0){
					$log['money'] 			= round((($result['capital']*CON_LATE_RATE*$late_result['late_days'])/2),2);
				}else{
					$log['money'] 			= round((($result['interest']*CON_LATE_RATE*$late_result['late_days'])/2),2);
				}
				
				$log['total'] 			= $user_account['total']+$log['money'];
				$log['use_money'] 		= $user_account['use_money']+$log['money'];
				$log['no_use_money'] 	= $user_account['no_use_money'];
				$log['collection'] 		= $user_account['collection'];
				$log['to_user'] 		= $data['user_id'];
				$log['remark'] 			= "[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html target=_blank>{$borrow_repayment_result['title']}</a>]借款标逾期并少于30天的逾期利息收入";
				$log['add_time'] 	= time();
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$result['user_id']}");
		
				//更新逾期的信息
				$this->db->query("update rsh_borrow_collection set late_days='{$late_result['late_days']}',late_interest='{$log['money']}' where id={$id}");
			}else{
				unset($value);
				
				$this->db->query("select p1.*,p2.user_id from rsh_borrow_collection as p1 left join rsh_borrow_tender as p2 on
						p1.tender_id=p2.id where p1.id=$id");
				$value 	= $query->row_array();
				$mode = substr(strval($value['user_id']),-1,1);
				
				//更新投资的信息
				$user_account = $this->Account_model->get_account($value['user_id']);
				$log['user_id'] 		= $value['user_id'];
				$log['ftype'] 			= LATE_COLLECTION;
				if($value['capital'] > 0){
					$log['money'] 			= round((($value['capital']*CON_LATE_RATE1*$late_result['late_days'])/2),2);
				}else{
					$log['money'] 			= round((($value['interest']*CON_LATE_RATE1*$late_result['late_days'])/2),2);
				}
				$log['total'] 			= $user_account['total']+$log['money'];
				$log['use_money'] 		= $user_account['use_money']+$log['money'];
				$log['no_use_money'] 	= $user_account['no_use_money'];
				$log['collection'] 		= $user_account['collection'];
				$log['to_user'] 		= $data['user_id'];
				$log['remark'] 			= "[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html target=_blank>{$borrow_repayment_result['title']}</a>]借款标逾期并少于30天的逾期利息收入";
				$log['add_time'] 		= time();
				$log['addip'] 			= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$value['user_id']}");
				
				//更新逾期的信息
				$this->db->query("update rsh_borrow_collection set late_days='{$late_result['late_days']}',late_interest='{$log['money']}' where id={$id}");
			}
		}
		
		//添加最后的还款金额
		$this->db->query("update rsh_borrow set  account_yes=account_yes-{$borrow_repayment_result['capital']},repayment_yesaccount= repayment_yesaccount + {$borrow_repayment_result['repay_account']} where id={$borrow_repayment_result['borrow_id']}");
		//$this->db->query("select count(*) as count from rsh_borrow_collection where tender_id in (select id from {borrow_tender} where borrow_id={$borrow_repayment_result['borrow_id']}) and status=0");
		if ($this->db->trans_status() === TRUE) {
	        $this->db->trans_commit();
	        return 1;
	    } else {
	        $this->db->trans_rollback();
	        //@todo 异常处理部分
	        return 0;
	    }
	}
	
	function sl_repay($data = array()){
		$id = $data['collection_id'];
		$ip = $data['ip'];
		$this->load->model('Account_model');
		$this->load->model('User_model');
		$this->load->model('Message_model');
		$this->load->model('Credit_model');
		
		$yestoday 	= strtotime(date('Y-m-d'));
		$nextday 	= strtotime(date('Y-m-d 23:59:59'));
		
		$query = $this->db->query("SELECT count(*) as count FROM rsh_borrow_collection
									WHERE repay_time>=$yestoday AND repay_time<=$nextday AND 
									fstatus=0 and id=$id ");
		$result_count = $query->row_array();
		/*if($result_count['count'] == 0){
			return "此借款还未到还款期，请不要乱操作";
		}*/
		
		$query = $this->db->query(" select p1.user_id,p1.id,p1.fstatus,p1.forder,p1.tender_id,p1.repay_time,p1.repay_yestime,
									p1.repay_account,p1.repay_yesaccount,p1.interest,p1.capital,p1.late_days,
									p1.interest,p1.add_time,p2.borrow_id,p2.account,p3.user_id as borrow_userid,
									p3.time_limit_day,p3.title,p3.style
									from rsh_borrow_collection as p1 left join rsh_borrow_tender as p2 
									on p1.tender_id=p2.id left join rsh_borrow as p3 on p2.borrow_id=p3.id 
									where p1.id=$id");
		
		$borrow_repayment_result = $query->row_array();
		$borrow_id 				 = $borrow_repayment_result["borrow_id"];
		$success_time 			 = $borrow_repayment_result["add_time"];
		$borrow_userid 			 = $borrow_repayment_result["borrow_userid"];
	
		if ($borrow_repayment_result['fstatus'] == 1){
			return "此借款已经还款，请不要乱操作";
		}
		
		//判断上一期是否已还
		if ($borrow_repayment_result['forder'] != 0){
			$_order = $borrow_repayment_result['forder'] - 1;
			$query_repay  = $this->db->query("select fstatus from rsh_borrow_collection where forder=$_order and borrow_id={$borrow_id}");
			$result_repay = $query_repay->row_array();
			if ($result_repay != false && $result_repay['fstatus'] != 1){
				return "你上期的借款还没还，请先还上期的";
			}
		}
		if($borrow_repayment_result['capital'] > 0){
			$late_result = late_interest($borrow_repayment_result['repay_time'], $borrow_repayment_result['capital']);
		}else{
			$late_result = late_interest($borrow_repayment_result['repay_time'], $borrow_repayment_result['interest']);
		}
		
		
		//判断可用余额是否够还款
		$user_account = $this->Account_model->get_account($borrow_userid);
		if ($user_account['use_money'] < $borrow_repayment_result['repay_account']+$late_result['late_interest']){
			return "账户余额不足，请充值。";
		}
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
    
		//扣除可用余额还款部分
		$bmode = $borrow_userid%100;
		$user_account = $this->Account_model->get_account($borrow_userid);
		$log['user_id'] 		= $borrow_userid;
		$log['ftype'] 			= REPAYMENT;
		$log['money'] 			= $borrow_repayment_result['repay_account'];
		$log['total'] 			= $user_account['total']-$log['money'];
		$log['use_money'] 		= $user_account['use_money']-$log['money'];
		$log['no_use_money'] 	= $user_account['no_use_money'];
		$log['collection'] 		= $user_account['collection'];
		$log['to_user'] 		= "0";
		$log['op'] 		= 1;
		$log['remark'] 			= "对[<a href='/borrow/slobj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]还款";
		$log['add_time'] 	= time();
		$log['addip'] 		= $ip;
		$this->db->insert('rsh_account_log_'.$bmode, $log);
		$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow_userid}");
			
		//判断是否是最后的还款，是则解冻借款担保金
		if ($borrow_repayment_result['capital'] > 0){
			$user_account = $this->Account_model->get_account($borrow_userid);
			$log['user_id'] 		= $borrow_userid;
			$log['ftype'] 			= BORROW_FROST;
			$log['money'] 			= $borrow_repayment_result['capital']*0.1;
			$log['total'] 			= $user_account['total'];
			$log['use_money'] 		= $user_account['use_money']+$log['money'];
			$log['no_use_money'] 	= $user_account['no_use_money']-$log['money'];
			$log['collection'] 		= $user_account['collection'];
			$log['to_user'] 		= "1";
			$log['remark'] 			= "对[<a href='/borrow/slobj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的解冻";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$bmode, $log);
			$this->db->query("update rsh_account set use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$borrow_userid}");
			
			//增加积分
			$this->Credit_model->incr_credit(array('user_id'=>$borrow_userid,
											'type_id'=>8,
											'op'=>1,
											'credit_value'=>$borrow_repayment_result['capital']/100,
											'remark'=>"借款成功加".($borrow_repayment_result['capital']/100)."分",
											'op_user'=>$borrow_repayment_result['user_id'],
											'add_time'=>time(),
											'addip'=>$ip));	
		}
		
		$_order = $borrow_repayment_result['forder'];
		
		//如果网站已经待还，就不用还
		if ($borrow_repayment_result['fstatus']!=2){
			$query = $this->db->query("select p1.*,p2.user_id from rsh_borrow_collection as p1 left join rsh_borrow_tender as p2 on p1.tender_id = p2.id where p1.forder='{$_order}' and p1.id='{$borrow_repayment_result['id']}'");
			$result = $query->result_array();
			foreach ($result as $key => $value){
				//更新投资人的分期信息
				$this->db->query("update rsh_borrow_collection set repay_yestime='".time()."',repay_yesaccount = repay_account,fstatus=1 where id = '{$value['id']}'");
				
				//更新投资的信息
				$interest_tmp = round($value['interest'], 2);
				$this->db->query(" update rsh_borrow_tender set repayment_yesaccount=repayment_yesaccount+{$value['repay_account']},
									wait_account=wait_account-{$value['repay_account']},wait_interest=wait_interest-{$interest_tmp},
									repayment_yesinterest=repayment_yesinterest+{$value['interest']} where id='{$value['tender_id']}'");
				$umode = $value['user_id']%100;
				$user_account = $this->Account_model->get_account($value['user_id']);
				$log['user_id'] 		= $value['user_id'];
				$log['ftype'] 			= INVEST_REPAYMENT;
				$log['money'] 			= $value['repay_account'];
				$log['total'] 			= $user_account['total'];
				$log['use_money'] 		= $user_account['use_money']+$log['money'];
				$log['no_use_money'] 	= $user_account['no_use_money'];
				$log['collection'] 		= $user_account['collection']-$log['money'];
				$log['to_user'] 		= $borrow_userid;
				$log['remark'] 			= "客户对[<a href='/borrow/slobj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款";
				$log['add_time'] 	= time();
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$umode, $log);
				$this->db->query("update rsh_account set use_money=use_money+{$log['money']},collection=collection-{$log['money']} where user_id={$value['user_id']}");
				
				//提醒设置
				$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$borrow_repayment_result['user_id'],
										'name'=>"客户对[<a href='/borrow/obj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"客户在".date("Y-m-d H:i:s")."对[<a href='/borrow/slobj/{$borrow_repayment_result['borrow_id']}.html' target=_blank>{$borrow_repayment_result['title']}</a>]借款的还款,还款金额为{$value['repay_account']}",
										'add_time'=>time(),'addip'=>$ip));
			}
		}
		
		//添加最后的还款金额
		//$this->db->query("update rsh_borrow set lz_endtime=verify_time+604800, account_yes=account_yes-{$borrow_repayment_result['capital']},repayment_yesaccount= repayment_yesaccount + {$borrow_repayment_result['repay_account']} where id={$borrow_repayment_result['borrow_id']}");
		$this->db->query("update rsh_borrow set  repayment_yesaccount= repayment_yesaccount + {$borrow_repayment_result['repay_account']} where id={$borrow_repayment_result['borrow_id']}");
		
		//$this->db->query("select count(*) as count from rsh_borrow_collection where tender_id in (select id from {borrow_tender} where borrow_id={$borrow_repayment_result['borrow_id']}) and status=0");
		if ($this->db->trans_status() === TRUE) {
	        $this->db->trans_commit();
	        return 1;
	    } else {
	        $this->db->trans_rollback();
	        //@todo 异常处理部分
	        return 1;
	    }
	}
	
	function user_borrow_total($user_id){
		$sql = "select fstatus,account,repayment_account,repayment_yesaccount from rsh_borrow where user_id=$user_id";
		$query = $this->db->query($sql);
		$borrow_list = $query->result_array();
		$num0 = 0;
		$num1 = 0;
		$num2 = 0;
		$num3 = 0;
		foreach($borrow_list as $borrow){
			if($borrow['fstatus'] == 3){
				$num0++;
				if($borrow['repayment_account'] != $borrow['repayment_yesaccount']){
					$num1++;	
				}else{
					$num3++;
				}
			}elseif($borrow['fstatus'] == 2){
				$num2++;
			}
		}
		$data['num0'] = $num0;
		$data['num1'] = $num1;
		$data['num2'] = $num2;
		$data['num3'] = $num3;
		return $data;
	}
	
	/**
	 * 获取用户投标总额
	 * @param $user_id
	 */
	function tender_total($user_id){
		$query = $this->db->query("select sum(money) as tender_total from rsh_borrow_tender where user_id=$user_id  and fstatus=1  and borrow_id in (select id from rsh_borrow where fstatus=3 and repayment_account > repayment_yesaccount ) ");
		$result = $query->row_array();
		return $result['tender_total'];
	}
	
	/**
	 * 获取用户正在投标总额
	 * @param $user_id
	 */
	function tender_ing_total($user_id){
		$_sql = "select sum(c.capital) as tender_total from rsh_borrow_collection c left join rsh_borrow b on  c.borrow_id = b.id   where c.user_id=$user_id and c.fstatus = 0 and b.fstatus >= 1 ";
		
		$query = $this->db->query($_sql);
		$result = $query->row_array();
		return $result['tender_total'];
	}

	/**
	 * 获取用户已收总额
	 * @param $user_id
	 */
	function collection_total($user_id, $fstatus = 0){
		
		$sql = "select sum(p1.repay_account) as collection_total,
			sum(p1.capital) as collection_capital,
			sum(p1.interest) as collection_interest 
			from rsh_borrow_collection as p1 
			left join rsh_borrow as p2 on p1.borrow_id=p2.id 
			left join rsh_borrow_tender as p3 on p1.tender_id=p3.id 
			where p1.user_id=$user_id and p1.fstatus=$fstatus 
			and p2.fstatus=3 and p3.transfer_status=0 ";
		$query = $this->db->query($sql);
		return $query->row_array();
	}
	
	/**
	 * 最近回款时间
	 * @param $user_id
	 */
	function first_collection_time($user_id){
		$query = $this->db->query("select repay_time from rsh_borrow_collection where user_id=$user_id and fstatus=0  and borrow_id in (select id from rsh_borrow where fstatus=3) order by repay_time asc limit 1");
		$result = $query->row_array();
		if(count($result) > 0){
			return $result['repay_time'];	
		}
		return 0;
	}
	

	/**
	 * 获取用户已收总额
	 * @param $user_id
	 */
	function repayment_total($user_id, $fstatus = -1){
		$where = " where user_id=".$user_id;
		if($fstatus != -1){
			$where .= " and fstatus=".$fstatus;
		}
		$query = $this->db->query("select sum(repayment_account) as repayment_account,sum(repayment_yesaccount) as repayment_yesaccount,sum(repayment_account) as repayment_account from rsh_borrow_repayment $where");
		return $query->row_array();
	}
	
	/**
	 * 借款户待还总额
	 * @param $user_id
	 * @param $fstatus
	 */
	function loan_repayment_total($user_id, $fstatus = -1){
		$where = " where borrow_id in (select id from rsh_borrow where user_id={$user_id} and fstatus=3) ";
		if($fstatus != -1){
			$where .= " and fstatus=".$fstatus;
		}
		$sql = "select sum(repay_account) as repay_account,sum(capital) as capital_account,sum(interest) as interest_account from rsh_borrow_collection $where ";
		$query = $this->db->query($sql);
		$result = $query->row_array();
		return $result;
	}
	
	/**
	 * 最近回款时间
	 * @param $user_id
	 */
	function first_repayment_time($user_id){
		$query = $this->db->query("select repayment_account,repayment_time from rsh_borrow_repayment where user_id=$user_id and fstatus=0 order by repayment_time asc limit 1");
		return $query->row_array();
	}

	/**
	 * 待收总额
	 * @param $user_id
	 */
	function collection_all_account(){
		$query = $this->db->query("select sum(repay_account) as collection_sum_account from 
									rsh_borrow_collection where fstatus=1  and borrow_id in (select id from rsh_borrow where fstatus=3)");
		return $query->row_array();
	}
	
	/**
	 * 待收总额
	 * @param $user_id
	 */
	function index_collection_all_account(){
		$mkey = "index_collection_all_account";
		$ret = $this->mycache->get($mkey);
		if($ret != false){
			return $ret;
		}
		$query = $this->db->query("select sum(repay_account) as collection_sum_account from
				rsh_borrow_collection where fstatus=1  and borrow_id in (select id from rsh_borrow where fstatus=3)");
		$result = $query->row_array();
		$this->mycache->set($mkey,$result['collection_sum_account'], 12*60*60);
		return $result['collection_sum_account'];
	}
	
	/**
	 * 投标列表
	 * @param unknown_type $data
	 * @return unknown
	 */
	function tenders_list($data){
		$_where = " where 1=1 and p2.time_limit>3";
		if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
			$strtime = strtotime($data['where']['strtime'].' 00:00:00');
			$_where .= " and p1.add_time >= ".$strtime;
		}
		if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
			$endtime = strtotime($data['where']['endtime'].' 23:59:59');
			$_where .= " and p1.add_time <= ".$endtime;
		}
		$sql = "select p1.id,p1.user_id,p3.username,p1.account,p1.add_time,p1.fstatus,p2.id as borrow_id,
				p2.title,p2.time_limit,p2.is_day,p2.time_limit_day,p2.ftype 
				from rsh_borrow_tender as p1 left join rsh_borrow as p2 on p1.borrow_id=p2.id 
				left join rsh_user as p3 on p1.user_id=p3.user_id $_where order by p1.user_id,p2.time_limit,p2.id";
		$query = $this->db->query($sql);
		$tender_list = $query->result_array();
		return $tender_list;
	}
	
	/**
	 * 回款排行榜
	 * @param $data
	 */
	function repayment_top($data =  array()){
		$_where = " where t1.fstatus=0 ";
		if(isset($data['where']['username']) && $data['where']['username'] != ''){
			$_where .= " and t2.username = '".$data['where']['username']."'";
		}
		
		if(isset($data['where']['strtime']) && $data['where']['strtime'] != 0){
			$strtime = strtotime($data['where']['strtime'].' 00:00:00');
			$_where .= " and t1.repay_time >= ".$strtime;
		}
		
		if(isset($data['where']['endtime']) && $data['where']['endtime'] != 0){
			$endtime = strtotime($data['where']['endtime'].' 23:59:59');
			$_where .= " and t1.repay_time <= ".$endtime;
		}
		
		$sql = "SELECT t1.user_id,t2.username,SUM(t1.repay_account) AS rc FROM rsh_borrow_collection AS t1
				LEFT JOIN rsh_user AS t2 ON t1.user_id=t2.user_id $_where 
				GROUP BY t1.user_id ORDER BY rc DESC LIMIT 0,10";
		$query = $this->db->query($sql);
		return $query->result_array();
	}
	
	/**
	 * 未还的净值标总额
	 * @param $user_id
	 */
	function no_repayment_borrow_3($user_id){
		$sql = "SELECT sum(p2.repayment_account) as money FROM rsh_borrow AS p1 
				LEFT JOIN rsh_borrow_repayment AS p2 ON p1.id=p2.borrow_id 
				WHERE p1.user_id={$user_id} AND p1.ftype=3 AND p2.fstatus=0";
		$query = $this->db->query($sql);
		$row = $query->row_array();
		if($row['money'] == null){
			return 0;
		}
		return $row['money'];
		/*
		$where = " where borrow_id in (select id from rsh_borrow where user_id={$user_id} and fstatus=3) ";
		if($fstatus != -1){
			$where .= " and fstatus=".$fstatus;
		}
		$sql = "select sum(repay_account) as repay_account,sum(capital) as capital_account,sum(interest) as interest_account from rsh_borrow_collection $where ";
		$query = $this->db->query($sql);
		$result = $query->row_array();
		return $result;
		*/
	}
	
	/**
	 * 获取用户净值标的最高罚息
	 * @param $user_id
	 */
	function jing_max_faxi($user_id){
		$sql = "SELECT SUM(apr/12/30*time_limit_day*30*".CON_LATE_RATE."*account) as money FROM rsh_borrow 
				WHERE user_id={$user_id} AND ftype=3 AND end_time>".time();
		$query = $this->db->query($sql);
		$row = $query->row_array();
		if($row['money'] == null){
			return 0;
		}
		return round($row['money'],2);
	}
		
	/**
	 * 正在招标的净值标
	 * @param $user_id
	 */
	function now_borrow_3($user_id){
		$sql = "select account from rsh_borrow where user_id={$user_id} and fstatus=1 limit 1";
		$query = $this->db->query($sql);
		$row = $query->row_array();
		if($row['account'] == null){
			return 0;
		}
		return $row['account'];
	}
	
	/**
	 * 后台统计汇总
	 */
	
	function admin_total_index(){
		//发标总额
		$sql = "select sum(account) as num from rsh_borrow where fstatus in(1,3)";
		$query = $this->db->query($sql);
		$row = $query->row_array();
		$result['up_borrow'] = $row['num'];
		
		//投标总额
		$sql_tender = "select sum(account) as num from rsh_borrow_tender where fstatus=1 and user_id not in (select user_id from rsh_user where is_self=1)";
		$query_tender = $this->db->query($sql_tender);
		$row_tender = $query_tender->row_array();
		$result['up_tender'] = $row_tender['num'];
		
		//利息
		$sqliterest = "select sum(repayment_account-account) as num from rsh_borrow where  fstatus in(1,3) and user_id not in(select user_id from rsh_user where is_self=1)";
		$query = $this->db->query($sqliterest);
		$row = $query->row_array();
		$result['up_iterest'] = $row['num'];
			
		//线上充值统计
		$sql_online = "select sum(money) as num from rsh_account_recharge where ftype=1 and fstatus=1 and user_id not in (select user_id from rsh_user where is_self=1)";
		$query_online = $this->db->query($sql_online);
		$row_online = $query_online->row_array();
		$result['up_recharge'] = $row_online['num'];
		
		//平台充值统计
		$sql_plat = "select sum(money) as num from rsh_account_recharge where ftype=0 and fstatus=1 and user_id not in (select user_id from rsh_user where is_self=1)";
		$query_plat = $this->db->query($sql_plat);
		$row_plat = $query_plat->row_array();
		$result['up_plat_recharge'] = $row_plat['num'];
		
			
		//回款统计
		$sql_repyament = "select sum(repay_yesaccount) as num from rsh_borrow_collection where fstatus=1 and user_id not in (select user_id from rsh_user where is_self=1)";
		$query_repayment = $this->db->query($sql_repyament);
		$row_repayment = $query_repayment->row_array();
		$result['up_repay'] = $row_repayment['num'];
			
		//冻结中的保证金总额
		
		//投标奖励
		$type = AWARD_ADD;
		$sql_awardadd = "select sum(money) as num from rsh_account_log where ftype={$type} and user_id not in (select user_id from rsh_user where is_self=1)";
		$query_awardadd = $this->db->query($sql_awardadd);
		$row_award = $query_awardadd->row_array();
		$result['up_award_add'] = $row_award['num'];
		
		//代收总额
		$sql_collection = "select sum(collection) as collection from rsh_account where user_id not in (select user_id from rsh_user where is_self=1)";
		$query_collection = $this->db->query($sql_collection);
		$row_collection = $query_collection->row_array();
		$result['up_collection'] = $row_collection['collection'];
		
		
		//提现总额
		$sql_tx = "SELECT SUM(total) as tx FROM rsh_account_cash WHERE fstatus IN(1,4) ";
		$query_tx = $this->db->query($sql_tx);
		$row_tx = $query_tx->row_array();
		$result['up_tx'] = $row_tx['tx'];
	
				
		//居间服务费
		$jjtype = TENDER_MANGE;
		$sql_jj = "select sum(money) as num from rsh_account_log where ftype={$jjtype}";
		$query_jj = $this->db->query($sql_jj);
		$row_jj = $query_jj->row_array();
		$result['up_jujian'] = $row_jj['num'];
		
		//提现手续费
		$sql_txfee = "SELECT SUM(fee) as tx FROM rsh_account_cash WHERE fstatus IN(1,4) ";
		$query_txfee = $this->db->query($sql_txfee);
		$row_txfee = $query_txfee->row_array();
		$result['up_txfee'] = $row_txfee['tx'];
		
		//会员总数
		$sqluser = "select count(user_id) as num from rsh_user where user_id not in(select user_id from rsh_user where is_self=1)";
		$queryuser = $this->db->query($sqluser);
		$row = $queryuser->row_array();
		$result['up_user_num'] = $row['num'];
		
		//VIP
		$sqluservip = "select count(user_id) as num from rsh_user_vip where vip_status = 1 and user_id not in(select user_id from rsh_user where is_self=1)";
		$queryvip = $this->db->query($sqluservip);
		$rowvip = $queryvip->row_array();
		$result['up_vip_num'] = $rowvip['num'];
		
		//身份认证
		$sqluserreal = "select count(user_id) as num from rsh_user where real_status = 1 and user_id not in(select user_id from rsh_user where is_self=1)";
		$queryreal = $this->db->query($sqluserreal);
		$rowreal = $queryreal->row_array();
		$result['up_real_num'] = $rowreal['num'];
		
		
		//手机认证
		$sqluserphone = "select count(user_id) as num from rsh_user where phone_status = 1 and user_id not in(select user_id from rsh_user where is_self=1)";
		$queryphone = $this->db->query($sqluserphone);
		$rowphone = $queryphone->row_array();
		$result['up_phone_num'] = $rowphone['num'];
		
		//EMAIL认证
		$sqluseremail = "select count(user_id) as num from rsh_user where email_status = 1 and user_id not in(select user_id from rsh_user where is_self=1)";
		$queryemail = $this->db->query($sqluseremail);
		$rowemail = $queryemail->row_array();
		$result['up_email_num'] = $rowemail['num'];
		
		//投资人总数
		$sql_user_count = "select count(DISTINCT(user_id)) as count from rsh_borrow_tender where user_id not in(select user_id from rsh_user where is_self=1)";
		$query = $this->db->query($sql_user_count);
		$result['tender_user_count'] = $query->row()->count;
			
		return $result;
	}
	
	
	/**
	 * 后台月统计
	 */
	function admin_index(){
		$key = 'admin_borrow_index';
		$result = $this->mycache->get_array($key);
		if (!$result){
			$result = array();
			/** 上个月 */
			//发标总额
			//$key = 'up_month_borrow';
			$start = strtotime("-1 month", strtotime(date('Y-m-01'))); 
			$end = strtotime(date("Y-m-01"));
			$sql = "select sum(account) as num from rsh_borrow where verify_time>={$start} and verify_time<{$end} and fstatus in(1,3)";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['up_month_borrow'] = $row['num'];
			
			//投标总额
			/*
			$sql = "select sum(account) as num from rsh_borrow_tender where add_time>={$start} and add_time<{$end} and fstatus=1";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['up_month_tender'] = $row['num'];
			*/
			
			//线上充值统计
			$sql = "select sum(money) as num from rsh_account_recharge where ftype=1 and fstatus=1 and add_time>={$start} and add_time<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['up_month_recharge'] = $row['num'];
			
			//回款统计
			$sql = "select sum(repay_yesaccount) as num from rsh_borrow_collection where fstatus=1 and repay_yestime>={$start} and repay_yestime<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['up_month_repay'] = $row['num'];
			
			//线下充值奖励统计
			$type = RECHARGE_REWARD;
			$sql = "select sum(money) as num from rsh_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['up_month_recharge_reward'] = $row['num'];
			
			//投标奖励
			$type = AWARD_ADD;
			$sql = "select sum(money) as num from rsh_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['up_month_award_add'] = $row['num'];
			
			//回款续投奖励
			$type = REPAYMENT_TENDER_REWARD;
			$sql = "select sum(money) as num from rsh_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['up_month_xutou'] = $row['num'];
			
			
			//////////////////////////////////////////////////////
			//当月发标总额
			$start = strtotime(date("Y-m-01"));
			$end = time();
			$sql = "select sum(account) as num from rsh_borrow where verify_time>={$start} and verify_time<{$end} and fstatus in(1,3)";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['this_month_borrow'] = $row['num'];
			
			//当月投标总额
			/*
			$sql = "select sum(account) as num from rsh_borrow_tender where add_time>={$start} and add_time<{$end} and fstatus=1";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['this_month_tender'] = $row['num'];
			*/
			
			//当月线上充值统计
			$sql = "select sum(money) as num from rsh_account_recharge where ftype=1 and fstatus=1 and add_time>={$start} and add_time<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['this_month_recharge'] = $row['num'];
			
			//当月回款统计
			$sql = "select sum(repay_yesaccount) as num from rsh_borrow_collection where fstatus=1 and repay_yestime>={$start} and repay_yestime<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['this_month_repay'] = $row['num'];
			
			//线下充值奖励统计
			$type = RECHARGE_REWARD;
			$sql = "select sum(money) as num from rsh_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['this_month_recharge_reward'] = $row['num'];
			
			//投标奖励
			$type = AWARD_ADD;
			$sql = "select sum(money) as num from rsh_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['this_month_award_add'] = $row['num'];
			
			//回款续投奖励
			$type = REPAYMENT_TENDER_REWARD;
			$sql = "select sum(money) as num from rsh_account_log where ftype={$type} and add_time>={$start} and add_time<{$end}";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$result['this_month_xutou'] = $row['num'];
			
			$this->mycache->set_array($key,$result,3600*6);
		}
		return $result;
	}
	
	/**
	 * 流转标的满标时间
	 * @param $id
	 */
	function lz_last_tender($id=0){
		if ($id>0){
			$key = "lz_last_tender_time_".$id;
			$ret = $this->mycache->get($key);
			if (!$ret){
				$sql = "select add_time from rsh_borrow_tender where borrow_id={$id} order by id desc limit 1";
				$query = $this->db->query($sql);
				$row = $query->row_array();
				$ret = $row['add_time'];
				$this->mycache->set($key,$ret,3600*24);
			}
			return $ret;
		}else{
			return false;
		}
	}

	/**
	 * 获取用户净值标的最高罚息
	 * @param $user_id
	 */
	function user_first_flag($user_id){
		$mode = substr(strval($user_id),-1,1);
		$today = time() - 24*60*60;
		$sql = "SELECT count(*) as count FROM rsh_account_log_{$mode} WHERE user_id={$user_id} AND add_time<{$today} and ftype=".COLLECTION;
		$query = $this->db->query($sql);
		$row = $query->row_array();
		if($row['count'] == null){
			return 0;
		}
		return $row['count'];
	}
	
	function user_first_tender($user_id){
		$sql = 'SELECT * from rsh_borrow_tender where user_id = '.$user_id.' ORDER BY add_time asc limit 1';
		$query = $this->db->query($sql);
		return $query->row_array();
	}
	
	/*function verify(){
		$sql = "select user_id,id,title,verify_time,repayment_time from rsh_borrow"
	}*/
	
	
	/**
	 * 
	 * 投资者撤回投资
	 */
	function borrow_review_single_false($data){
		$this->load->model('Account_model');
		$borrow_tender_id = intval($data['id']);
		$ip = $data['ip'];
		$data['select'] = 1;
		$tender_obj = $this->get_borrow_tender_obj($borrow_tender_id,$data);
		
		$borrow = $this->get_borrow_obj($tender_obj['borrow_id']);
		if ($tender_obj && $tender_obj['fstatus'] != 3 && $borrow['work_time']==2)
		{
			$tender_obj['b_uid'] = $borrow['user_id'];
			$tender_obj['ip'] = $ip;
			$this->get_account_log($tender_obj);
			
			$this->db->query("update rsh_borrow_collection set fstatus=3 where tender_id={$tender_obj['id']}");
			$this->db->query("update rsh_borrow_tender set fstatus=3 where id={$tender_obj['id']}");
		
			//更新投标表(借到的资金和投标的次数)
			$this->db->query("update rsh_borrow set account_yes=account_yes-{$tender_obj['account']},tender_times=tender_times-1 where id={$borrow['id']}");
			return 1;
		}else{
			return 0;
		}
		
	}
	
	function get_account_log($tmp){
		$red_money =$tmp['money'] - $tmp['account'];
		
		$mode = substr(strval($tmp['user_id']),-1,1);
		$user_account = $this->Account_model->get_account($tmp['user_id']);
		$log['user_id'] 	= $tmp['user_id'];
		$log['ftype'] 		= INVEST_SINGLE_FALSE;
		$log['money'] 		= $tmp['account']; //投资者投标金额
		$log['total'] 		= $user_account['total']; //账户总额
		$log['use_money'] 	= $user_account['use_money']+$log['money']; //可用金额+投资者投标金额
		$log['no_use_money']= $user_account['no_use_money']-$log['money']; //冻结资金-投资者投标金额
		$log['collection'] 	= $user_account['collection']; //待收金额
		$log['to_user'] 	= $tmp['b_uid']; //招标者ID
		$log['remark'] 		= "单个撤标返回的投标额";
		$log['add_time'] 	= time();
		$log['addip'] 		= $tmp['ip'];
		$this->db->insert('rsh_account_log_'.$mode, $log);
		//by liub 20150126 红包返回
		//注释 ：$set_account = "use_money=use_money+{$log['money']},no_use_money=no_use_money-{$log['money']}";
		$set_account = "total = total - {$red_money},use_money=use_money+{$tmp['account']},no_use_money=no_use_money-{$tmp['money']},red_money = red_money+{$red_money}";
		$this->db->query("update rsh_account set {$set_account} where user_id={$tmp['user_id']}");
	}
	
	
	function get_count_auto_tender(){
		$key = 'auto_tender_count';
		$this->mycache->delete($key);
		$num = $this->mycache->get($key);
		
		$valid = strtotime('2014-04-17 10:00:00')+2*3600*24;
		$now = time();
				
		if (!$num){
			$sql = "SELECT COUNT(*) as num FROM rsh_borrow_auto WHERE fstatus=1 AND is_del=0";
			
			if($now>$valid){
				$sql .= " AND valid_start_time<{$now} AND valid_end_time>{$now}";
			}
			
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$num = $row['num'];
			$this->mycache->set($key,$num,900);
		}
		return $num;
	}
	
	function borrow_sl_tender($data = array()){
		$id 		= $data['id'];
		$ip 		= $data['ip'];
		$user_id 	= $data['user_id'];
		$money 		= $data['money'];
		$account 	= $data['account'];
		$borrow 	= self::get_borrow_obj($data['id']);
		$this->load->model('Account_model');
		$this->load->model('User_model');
		$this->load->model('Message_model');
		$this->load->model('Credit_model');
		$borrow_url 	= "<a href='/borrow/slobj/{$borrow['id']}.html' target=_blank>{$borrow['title']}</a>";
		/*tangc 死锁问题*/
		$this->db->trans_strict(FALSE);
    	$this->db->trans_begin();
		//第一次投标，更新标状态和复审时间复审备注
		if($borrow['tender_times'] < 1){
			$this->db->query("update rsh_borrow set fstatus=3,repayment_time=".time().",repayment_remark='自动复审' where id={$borrow['id']}");
		}
		//更新投标次数和已借入金额
		$this->db->query("update rsh_borrow set account_yes=account_yes+{$data['account']},tender_times=tender_times+1  where id='{$borrow['id']}'");
		//新增投标记录
		$t2data['add_time']  	= time();
		$t2data['addip']  		= $ip;
		$t2data['user_id']  	= $user_id;
		$t2data['borrow_id ']  	= $id;
		$t2data['money']  		= $money;
		$t2data['account']  	= $account;
		$t2data['fstatus']  	= 1;
		$this->db->insert('rsh_borrow_tender', $t2data);
		$tender_id = $this->db->insert_id();
		
		if ($tender_id>0){
			$eq['account'] 			= $account;
			$eq['apr'] 				= $borrow['apr'];
			$eq['time_limit'] 		= $borrow['time_limit'];
			$eq['style'] 			= $borrow['style'];
	        $eq['is_day']			= $borrow['is_day'];
	        $eq['time_limit_day']	= $borrow['time_limit_day'];
			$result 				= equal_interest($eq);
			$_repay_time = time()+$borrow['time_limit_day']*60*60*24;
			$repayment_account 		= 0;
			//添加待收明细
			foreach ($result as $key => $value){
				$repayment_account += $value['repayment_account'];
				//将归还信息写进去
				$this->db->query("insert into rsh_borrow_collection set user_id=$user_id,borrow_id=$id,add_time=".time().",addip='{$ip}',
						`tender_id`='{$tender_id}',`forder`='{$key}',`repay_time`='{$_repay_time}',
						`repay_account`='{$value['repayment_account']}',`interest`='{$value['interest']}',
						`capital`='{$value['capital']}'");
			}
			$_interest = round($repayment_account-$data['account'],2);
			$this->db->query(" update rsh_borrow_tender set repayment_account='{$repayment_account}',
								wait_account ='{$repayment_account}',interest = '{$_interest}',
								wait_interest = '{$_interest}' where id={$tender_id}");
			
			//投标金额冻结
			$mode = substr(strval($user_id),-1,1);
			$account_result 	= $this->Account_model->get_account($user_id);
			$log['user_id'] 	= $user_id;
			$log['ftype'] 		= TENDER;
			$log['money'] 		= $account;
			$log['total'] 		= $account_result['total'];
			$log['use_money'] 	= $account_result['use_money']-$log['money'];
			$log['no_use_money']= $account_result['no_use_money']+$log['money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "投标冻结资金";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$user_id}");
			
			
			//扣除投资者的金钱。
			unset($account_result);
			unset($log);
			$account_result 	= $this->Account_model->get_account($user_id);
			$log['user_id'] 	= $user_id;
			$log['ftype'] 		= INVEST;
			$log['money'] 		= $account;
			$log['total'] 		= $account_result['total']-$log['money'];
			$log['use_money'] 	= $account_result['use_money'];
			$log['no_use_money']= $account_result['no_use_money']-$log['money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "投标成功费用扣除";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$user_id}");
			
			
			//添加待收的金额
			unset($account_result);
			unset($log);
			$account_result 	= $this->Account_model->get_account($user_id);
			$log['user_id'] 	= $user_id;
			$log['ftype'] 		= COLLECTION;
			$log['money'] 		= $repayment_account;
			$log['total'] 		= $account_result['total']+$log['money'];
			$log['use_money'] 	= $account_result['use_money'];
			$log['no_use_money']= $account_result['no_use_money'];
			$log['collection'] 	= $account_result['collection']+$log['money'];
			$log['to_user'] 	= $borrow['user_id'];
			$log['remark'] 		= "待收金额";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode, $log);
			$this->db->query("update rsh_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$user_id}");
			
			//提醒设置
			$this->Message_model->send(array('sent_user'=>1,'receive_user'=>$user_id,
										'name'=>"投资的标[<font color=red>{$borrow['title']}</font>投标成功",
										'fstatus'=>0,'message_type'=>'system','sented'=>0,'deltype'=>0,
										'content'=>"你所投资的标[<a href='/borrow/slobj/{$id}.html' target=_blank><font color=red>{$borrow['title']}</font></a>]在".date("Y-m-d",time())."已经通过",
										'add_time'=>time(),'addip'=>$ip));
			
			/*if ($borrow['is_day']==1){
				$credit_value = round($account/100*$borrow['apr']/100*($borrow['time_limit_day']/30));
			}else{
				$credit_value = round($account/100*$borrow['apr']/100*$borrow['time_limit']);
			}
			
			//增加积分
			$creditNidType = $this->Credit_model->arrays('creditNidType');
			$creditTypeName = $this->Credit_model->arrays('creditTypeName');
			$credit_log = array('user_id'=>$user_id,
								'type_id'=>$creditNidType['invest_success'],
								'op'=>1,
								'credit_value'=>$credit_value,
								'remark'=>$creditTypeName[$creditNidType['invest_success']].'加'.$credit_value.'分',
								'op_user'=>$borrow['user_id'],
								'add_time'=>time(),
								'addip'=>$ip);
			$this->Credit_model->incr_credit($credit_log);	*/
			
			//借款者总金额增加。
			unset($account_result);
			unset($log);
			$mode1 = $borrow['user_id']%100;
			$account_result 	= $this->Account_model->get_account($borrow['user_id']);
			$log['user_id'] 	= $borrow['user_id'];
			$log['ftype'] 		= BORROW_SUCCESS;
			$log['money'] 		= $account;
			$log['total'] 		= $account_result['total']+$log['money'];
			$log['use_money'] 	= $account_result['use_money']+$log['money'];
			$log['no_use_money']= $account_result['no_use_money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= "0";
			$log['remark'] 		= "通过[{$borrow_url}]借到的款";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode1, $log);
			$this->db->query("update rsh_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$borrow['user_id']}");
			
			//冻结借款标的保证金10%。
			unset($account_result);
			unset($log);
			$account_result 	= $this->Account_model->get_account($borrow['user_id']);
			$log['user_id'] 	= $borrow['user_id'];
			$log['ftype'] 		= MARGIN;
			$log['money'] 		= $data['account']*0.1;
			$log['total'] 		= $account_result['total'];
			$log['use_money'] 	= $account_result['use_money']-$log['money'];
			$log['no_use_money'] = $account_result['no_use_money']+$log['money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= "0";
			$log['remark'] 		= "冻结借款标的[{$borrow_url}]的保证金";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			//如果保证金等于0，那不在写记录了
            if($log['money']<>0){
				$this->db->insert('rsh_account_log_'.$mode1, $log);
				$this->db->query("update rsh_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$borrow['user_id']}");
				//更新保证金
				$this->db->query("update rsh_borrow set forst_account=forst_account+{$log['money']} where id='{$borrow['id']}'");
			}
			
			//借款手续费
			unset($account_result);
			unset($log);
            $borrow_fee = 0;
			$borrow_fee = round($borrow['time_limit']*0.005*$account,2);	
			$account_result 	=  $this->Account_model->get_account($borrow['user_id']);
			$log['user_id'] 	= $borrow['user_id'];
			$log['ftype'] 		= BORROW_FEE;
			$log['money'] 		= $borrow_fee;
			$log['total'] 		= $account_result['total']-$log['money'];
			$log['use_money'] 	= $account_result['use_money']-$log['money'];
			$log['no_use_money']= $account_result['no_use_money'];
			$log['collection'] 	= $account_result['collection'];
			$log['to_user'] 	= "0";
			$log['remark'] 		= "借款[{$borrow_url}]的手续费";
			$log['add_time'] 	= time();
			$log['addip'] 		= $ip;
			$this->db->insert('rsh_account_log_'.$mode1, $log);
			$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");
			
			$nowtime = time();
			$endtime = time()+$borrow['time_limit_day']*60*60*24;
			$_each_time = date('m月d日',$endtime);
			$this->db->query("update rsh_borrow set success_time='{$nowtime}',end_time='{$endtime}',each_time='{$_each_time}',
					 			payment_account=payment_account+'{$repayment_account}'
					 			where id='{$borrow['id']}'");
			
			
			//如果有设置奖励并且招标成功
			if ($borrow['award'] == 2 || $borrow['funds'] > 0){
				//投标奖励扣除和增加。
				$money = round((($borrow['funds']/100)*$account),2);	
				
				unset($account_result);
				unset($log);
				$account_result  = $this->Account_model->get_account($user_id);
				$log['user_id'] 		= $user_id;
				$log['ftype'] 			= AWARD_ADD;
				$log['money'] 			= $money;
				$log['total'] 			= $account_result['total']+$log['money'];
				$log['use_money'] 		= $account_result['use_money']+$log['money'];
				$log['no_use_money'] 	= $account_result['no_use_money'];
				$log['collection'] 		= $account_result['collection'];
				$log['to_user'] 		= $borrow['user_id'];
				$log['remark'] 			= "借款[{$borrow_url}]的奖励";
				$log['add_time'] 		= time();
				$log['addip'] 			= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$user_id}");
			
				unset($account_result);
				unset($log);
				$account_result 	= $this->Account_model->get_account($borrow['user_id']);
				$log['user_id'] 	= $borrow['user_id'];
				$log['ftype'] 		= AWARD_LOWER;
				$log['money'] 		= $money;
				$log['total'] 		= $account_result['total']-$log['money'];
				$log['use_money'] 	= $account_result['use_money']-$log['money'];
				$log['no_use_money']= $account_result['no_use_money'];
				$log['collection'] 	= $account_result['collection'];
				$log['to_user'] 	= $user_id;
				$log['remark'] 		= "扣除借款[{$borrow_url}]的奖励";
				$log['add_time'] 	= time();
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$mode1, $log);
				$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$borrow['user_id']}");
			}
			
				if ($this->db->trans_status() === TRUE) {
		        	$this->db->trans_commit();
		        	return 1;
			    } else {
			        $this->db->trans_rollback();
			        //@todo 异常处理部分
			        return 0;
			    }
				
			}else{
				$this->db->trans_rollback();
				return 0;
			}
		
		
	}
	
	/**
	 * 流转标撤销投标
	 */
	function tender_cancel($id){
		
		$this->load->model('Account_model');
		$this->db->where('id', $id);
		$query = $this->db->get('rsh_borrow_tender');
		$tender = $query->row_array();
		$time = time();
		$ip = $this->js->get_ip();
		
		if (isset($tender['id']) && $tender['fstatus']==1){
			if ($tender['repayment_yesaccount']>0){
				return '该投资部分已还，不能撤销';
			}else{
				
				/*tangc 死锁问题*/
				$this->db->trans_strict(FALSE);
		    	$this->db->trans_begin();
		    
				$mode = $tender['user_id']%100;
				
				//撤销投标待收扣除
				$account_result  	= $this->Account_model->get_account($tender['user_id']);
				$log['user_id'] 	= $tender['user_id'];
				$log['ftype'] 		= INVEST_CANCEL_COLL;
				$log['money'] 		= $tender['repayment_account'];
				$log['total'] 		= $account_result['total']-$log['money'];
				$log['use_money'] 	= $account_result['use_money'];
				$log['no_use_money']= $account_result['no_use_money'];
				$log['collection'] 	= $account_result['collection']-$log['money'];
				$log['to_user'] 	= "0";
				$log['op'] 	= 1;
				$log['remark'] 		= "撤销投标待收扣除";
				$log['add_time'] 	= $time;
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total-{$log['money']},collection=collection-{$log['money']} where user_id={$tender['user_id']}");
				unset($log);
				
				//撤销投标本金返回
				$account_result  	= $this->Account_model->get_account($tender['user_id']);
				$log['user_id'] 	= $tender['user_id'];
				$log['ftype'] 		= INVEST_CANCEL_ACC;
				$log['money'] 		= $tender['account'];
				$log['total'] 		= $account_result['total']+$log['money'];
				$log['use_money'] 	= $account_result['use_money']+$log['money'];
				$log['no_use_money']= $account_result['no_use_money'];
				$log['collection'] 	= $account_result['collection'];
				$log['to_user'] 	= "0";
				$log['remark'] 		= "撤销投标本金返回";
				$log['add_time'] 	= $time;
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total+{$log['money']},use_money=use_money+{$log['money']} where user_id={$tender['user_id']}");
				unset($log);
				
				//撤销投标奖励扣除
				$this->db->where('id', $tender['borrow_id']);
				$query = $this->db->get('rsh_borrow');
				$borrow = $query->row_array();
				if ($borrow['funds']>0){
					$money = round((($borrow['funds']/100)*$tender['account']),2);
					$account_result  	= $this->Account_model->get_account($tender['user_id']);
					$log['user_id'] 	= $tender['user_id'];
					$log['ftype'] 		= INVEST_CANCEL_AWARD;
					$log['money'] 		= $money;
					$log['total'] 		= $account_result['total']-$log['money'];
					$log['use_money'] 	= $account_result['use_money']-$log['money'];
					$log['no_use_money']= $account_result['no_use_money'];
					$log['collection'] 	= $account_result['collection'];
					$log['to_user'] 	= "0";
					$log['remark'] 		= "撤销投标奖励扣除";
					$log['add_time'] 	= $time;
					$log['addip'] 		= $ip;
					$this->db->insert('rsh_account_log_'.$mode, $log);
					$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$tender['user_id']}");
					unset($log);
				}
				
				//如果此次投标有用到体验金  则扣除体验金
				$sql = "SELECT SUM(exp_money) AS expmoney FROM rsh_expmoney_deduct WHERE collection_id IN(SELECT id FROM rsh_borrow_collection WHERE tender_id={$id})";
				$query = $this->db->query($sql);
				$tmpRow = $query->row_array();
				$expMoney = $tmpRow['expmoney'] ? $tmpRow['expmoney'] : 0;
				if ($expMoney>0){
					//扣除体验金
					$account_result  	= $this->Account_model->get_account($tender['user_id']);
					$log['user_id'] 	= $tender['user_id'];
					$log['ftype'] 		= EXP_MONEY_DEDUCT;
					$log['money'] 		= $expMoney;
					$log['total'] 		= $account_result['total']-$log['money'];
					$log['use_money'] 	= $account_result['use_money']-$log['money'];
					$log['no_use_money']= $account_result['no_use_money'];
					$log['collection'] 	= $account_result['collection'];
					$log['to_user'] 	= "0";
					$log['op'] 	= 1;
					$log['remark'] 		= "撤销投标扣除返回的体验金";
					$log['add_time'] 	= $time;
					$log['addip'] 		= $ip;
					$this->db->insert('rsh_account_log_'.$mode, $log);
					$this->db->query("update rsh_account set total=total-{$log['money']},use_money=use_money-{$log['money']} where user_id={$tender['user_id']}");
					$this->db->query("delete from rsh_expmoney_deduct WHERE collection_id IN(SELECT id FROM rsh_borrow_collection WHERE tender_id={$id})");
					unset($log);
				}
				
				
				
				/********* 流转标额度不空出，用内部账户填补 **************/
				$tuid = 329;
				$tmpTender = $tender;
				unset($tmpTender['id']);
				$tmpTender['user_id'] = $tuid;
				$tmpTender['add_time'] = $time;
				$this->db->insert('rsh_borrow_tender', $tmpTender);
				$new_tender_id = $this->db->insert_id();
				
				//投标金额冻结
				$mode = $tuid%100;
				$account_result 	= $this->Account_model->get_account($tuid);
				$log['user_id'] 	= $tuid;
				$log['ftype'] 		= TENDER;
				$log['money'] 		= $tender['account'];
				$log['total'] 		= $account_result['total'];
				$log['use_money'] 	= $account_result['use_money']-$log['money'];
				$log['no_use_money']= $account_result['no_use_money']+$log['money'];
				$log['collection'] 	= $account_result['collection'];
				$log['to_user'] 	= $borrow['user_id'];
				$log['op'] = 1;
				$log['remark'] 		= "投标冻结资金";
				$log['add_time'] 	= $time;
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set use_money=use_money-{$log['money']},no_use_money=no_use_money+{$log['money']} where user_id={$tuid}");
			
				//扣除投资者的金钱。
				unset($log);
				$account_result 	= $this->Account_model->get_account($tuid);
				$log['user_id'] 	= $tuid;
				$log['ftype'] 		= INVEST;
				$log['money'] 		= $tender['account'];
				$log['total'] 		= $account_result['total']-$log['money'];
				$log['use_money'] 	= $account_result['use_money'];
				$log['no_use_money']= $account_result['no_use_money']-$log['money'];
				$log['collection'] 	= $account_result['collection'];
				$log['to_user'] 	= $borrow['user_id'];
				$log['remark'] 		= "投标成功费用扣除";
				$log['add_time'] 	= $time;
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total-{$log['money']},no_use_money=no_use_money-{$log['money']} where user_id={$tuid}");
				
				//添加待收的金额
				unset($log);
				$account_result 	= $this->Account_model->get_account($tuid);
				$log['user_id'] 	= $tuid;
				$log['ftype'] 		= COLLECTION;
				$log['money'] 		= $tender['repayment_account'];
				$log['total'] 		= $account_result['total']+$log['money'];
				$log['use_money'] 	= $account_result['use_money'];
				$log['no_use_money']= $account_result['no_use_money'];
				$log['collection'] 	= $account_result['collection']+$log['money'];
				$log['to_user'] 	= $borrow['user_id'];
				$log['remark'] 		= "待收金额";
				$log['add_time'] 	= $time;
				$log['addip'] 		= $ip;
				$this->db->insert('rsh_account_log_'.$mode, $log);
				$this->db->query("update rsh_account set total=total+{$log['money']},collection=collection+{$log['money']} where user_id={$tuid}");
				
				//待收明细改成补标人的
				$sql = "update rsh_borrow_collection set user_id={$tuid},tender_id={$new_tender_id} where tender_id={$id}";
				$this->db->query($sql);
				//原投标记录表状态-取消
				$sql = "update rsh_borrow_tender set fstatus=2 where id={$id}";
				$this->db->query($sql);
				
				if ($this->db->trans_status() === TRUE) {
			        $this->db->trans_commit();
			       	return '操作成功';
			    } else {
			        $this->db->trans_rollback();
			        //@todo 异常处理部分
			       return '操作失败';
			    }
			
			}
		}else{
			return '数据错误';
		}
		
		
	}
	
	function guarantee_add($data){
		$this->db->insert('rsh_borrow_guarantee', $data);
		$this->mycache->delete('get_guarantee_borrow_list');
		$this->mycache->delete('rsh_guarantee_name_list');
		return $this->db->insert_id();
	}
	
	function guarantee_update($id,$data){
		$this->db->where('id', $id);
		$this->db->update('rsh_borrow_guarantee', $data);
		$this->mycache->delete('get_guarantee_borrow_list');
		$this->mycache->delete('rsh_guarantee_name_list');
		return $this->db->affected_rows();
	}
	
	function get_guarantee_borrow_list(){
		$mkey = "get_guarantee_borrow_list";
		
		$ret = $this->mycache->get_array($mkey);
		if($ret != false){
			return $ret;
		}
		
		$select = "id,name";
		
		//封装条件
		$_where = " where is_del=0 ";
				
		//排序
		$_order  = " order by id desc ";
		
		//封装sql
		$sql_result = "select $select from rsh_borrow_guarantee ";
		$sql_result .= $_where;
		$sql_result .= $_order;
		
		$query = $this->db->query($sql_result);
		$borrow_guarantee_list = $query->result_array();
		if(count($borrow_guarantee_list) < 1){
			return array();
		}
		$this->mycache->set_array($mkey,$borrow_guarantee_list);
		return $borrow_guarantee_list;
	}
	
	function get_guarantee_list($parms=array(),$per_page=0,$page_size=20){
		$tmp = array();
		foreach($parms as $key => $val){
			if($key == 'is_del'){
				$tmp[] = "`{$key}` = '{$val}'";
			}
			
			if($val){
				if($key == 'name'){
					$tmp[] = "`{$key}` like '%{$val}%'";
				}else{
					$tmp[] = "`{$key}` = '{$val}'";
				}
			}
		}
		
		$select = "*";
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);
		$order = "order by id asc";
		$limit = " limit {$per_page},{$page_size}";
		$sql = "select {$select} from rsh_borrow_guarantee {$where} {$order} {$limit}";
		$query = $this->db->query($sql);
		$data['list'] = $query->result_array();
		$sql = "select count(*) as count from rsh_borrow_guarantee {$where}";
		$query = $this->db->query($sql);
		$data['count'] = $query->row()->count;
		return $data;
	}
	
	function get_borrow_guarantee_obj($id){
		$select = "*";
		$this->db->select($select);
		$this->db->where('id', $id);
		$query = $this->db->get('rsh_borrow_guarantee');
		return $query->row_array();
	}
	
	function get_guarantee_name_list(){
		$key = 'rsh_guarantee_name_list';
		$list = $this->mycache->get_array($key);
		if(!$list){
			$this->db->select('id,name');		
			$query = $this->db->get('rsh_borrow_guarantee');		
			$result = $query->result_array();
			$list = array();
			if($result){
				foreach($result as $v){
					$list[$v['id']] = $v['name'];
				}
				$this->mycache->set_array($key,$list);
			}
		}
		return $list;
	}
	
	function apply_add($data){
		$this->db->insert('rsh_borrow_apply', $data);
		return $this->db->insert_id();		
	}
	
	function get_borrow_apply_list($parms=array(),$per_page=0,$page_size=20){
		$tmp = array();
		foreach($parms as $key => $val){
			if($val){
				$tmp[] = "`{$key}` = '{$val}'";
			}
		}
		
		$select = "*";
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);
		$order = "order by id asc";
		$limit = " limit {$per_page},{$page_size}";
		$sql = "select {$select} from rsh_borrow_apply {$where} {$order} {$limit}";
		$query = $this->db->query($sql);
		$data['list'] = $query->result_array();
		$sql = "select count(*) as count from rsh_borrow_apply {$where}";
		$query = $this->db->query($sql);
		$data['count'] = $query->row()->count;
		return $data;
	}
	
	function get_by_apply_borrow($id){
		$select = "*";
		$this->db->select($select);
		$this->db->where('id', $id);
		$query = $this->db->get('rsh_borrow_apply');
		return $query->row_array();
	}
	
	function get_tender_rank($data){
			$start = $data['where']['start'];
			$end = $data['where']['end'];
			$_where = " where 1=1 ";
			
			
			if($start > 0){
				$_where .=" t1.add_time>$start and t1.add_time<$end ";	
			}
			
			
			$sql = "select sum(t1.account) as money,count(DISTINCT(t1.user_id)) as tender_count,t2.username ,t2.user_id,t2.add_time,t4.online_recharge,t6.cash_money from rsh_borrow_tender t1 left join 
			rsh_user t2 on t1.user_id=t2.user_id
			left join rsh_borrow t3 on t1.borrow_id=t3.id 
			left join (SELECT user_id,SUM(money) AS online_recharge FROM rsh_account_recharge WHERE  FSTATUS=1 GROUP BY user_id) AS t4 ON t2.user_id=t4.user_id
			left join (SELECT user_id,SUM(total) AS cash_money FROM rsh_account_cash WHERE  fstatus=1 GROUP BY user_id) AS t6 ON t2.user_id=t6.user_id
			$_where GROUP BY t1.user_id ORDER BY money DESC,t1.add_time ASC ";
			
			
			if(isset($data['limit']) && $data['limit'] == 'all'){
					$query = $this->db->query($sql);
					$data['tender_rank_list'] = $query->result_array();
					return $data;
			}
			
			$_limit = " limit ".$data['page_start'].",".$data['page_size'];
			$sql .= $_limit;
			$query = $this->db->query($sql);
			$data['tender_rank_list']  = $query->result_array();
			
			
			//总记录条数
			$sql_count = "select  count(*) as count from rsh_borrow_tender t1 left join 
			rsh_user t2 on t1.user_id=t2.user_id
			left join rsh_borrow t3 on t1.borrow_id=t3.id 
			left join (SELECT user_id,SUM(money) AS online_recharge FROM rsh_account_recharge WHERE  FSTATUS=1 GROUP BY user_id) AS t4 ON t2.user_id=t4.user_id
			left join (SELECT user_id,SUM(total) AS cash_money FROM rsh_account_cash WHERE  fstatus=1 GROUP BY user_id) AS t6 ON t2.user_id=t6.user_id";
			$sql_count .= $_where;
			$query = $this->db->query($sql_count);
			$data['tender_rank_count'] = $query->row()->count;
			
			return $data;
			
		
	}
	
	
	function managemoney($data){
		$start_time = $data['start_time'];
		$end_time 	= $data['end_time'];
		
		//累计理财投标总额
		$sql1 = "select sum(account) as caccount from rsh_borrow_tender where fstatus=1 and add_time<$end_time";
		$query = $this->db->query($sql1);
		$ret1 = $query->row_array();
		$retData['caccount'] = $ret1['caccount'];
		 
		//本月新增理财总额
		$sql2 = "select sum(account) as saccount from rsh_borrow_tender where add_time>$start_time and add_time<$end_time and fstatus=1";
		$query = $this->db->query($sql2);
		$ret2 = $query->row_array();
		$retData['saccount'] = $ret2['saccount'];
		//累计理财会员数
		$sql3 = "SELECT COUNT(DISTINCT user_id) AS useracount FROM rsh_borrow_tender WHERE  add_time>$start_time and add_time<$end_time and fstatus=1";
		$query = $this->db->query($sql3);
		$ret3 = $query->row_array();
		$retData['useracount'] = $ret3['useracount'];
		
		//新增理财会员数
		$sql4 = "SELECT COUNT(DISTINCT user_id) AS useracount FROM rsh_borrow_tender WHERE fstatus=1 and user_id in (select user_id from rsh_user where add_time>$start_time and add_time<$end_time and type_id=2) ";
		$query = $this->db->query($sql4);
		$ret4 = $query->row_array();
		$retData['museracount'] = $ret4['useracount'];
		
		//本月理财人数
		$sql5 = "SELECT COUNT(DISTINCT user_id) AS useracount FROM rsh_borrow_tender WHERE fstatus=1 and add_time>$start_time and add_time<$end_time ";
		$query = $this->db->query($sql5);
		$ret5 = $query->row_array();
		$retData['mtuseracount'] = $ret5['useracount'];
		
		//人均理财金额=本月新增理财总额/本月理财人数
		$retData['rjtmoney'] = $retData['saccount']/$retData['mtuseracount'];
		
		//每标人均投标金额= 本月标的总额/本月理财人数
		$sql6 = "SELECT sum(account) as baccount FROM rsh_borrow WHERE fstatus=3 and verify_time>$start_time and verify_time<$end_time ";
		$query = $this->db->query($sql6);
		$ret6 = $query->row_array();
		$retData['baccount'] = $ret6['baccount'];
		//$retData['baccount'] = $retData['baccount']/$retData['mtuseracount'];
		//人均投资债权标数量
		$sql7 = "SELECT count(*) as ccount FROM rsh_creditor_obj WHERE fstatus=3";
		$query = $this->db->query($sql7);
		$ret7 = $query->row_array();
		$retData['ccount'] = $ret7['ccount'];
		
		$sql8 = "SELECT COUNT(DISTINCT user_id) AS useracount FROM rsh_creditor_log WHERE fstatus=3";
		$query = $this->db->query($sql8);
		$ret8 = $query->row_array();
		$retData['cuseracount'] = $ret8['useracount'];
		$retData['rjcnum'] = $retData['ccount']/$retData['cuseracount'];
		
		//人均账户余额
		$sql9 = "select user_id from rsh_user where add_time<$end_time";
		$query = $this->db->query($sql9);
		$ret9 = $query->result_array();
		$totalusemoney = 0;
		foreach($ret9 as $v){
			$mode = $v['user_id']%10;
			$query = $this->db->query("SELECT * FROM rsh_account_log_$mode WHERE user_id='{$v['user_id']}' AND `add_time`<=$end_time ORDER BY add_time desc,id DESC LIMIT 1;");
			$row = $query->row_array();
			$totalusemoney += isset($row['use_money']) ? $row['use_money'] : 0;
		}
		$retData['rjye'] = $totalusemoney/count($ret9);
		
		//总计VIP会员数
		$sql10 = "SELECT count(*) as vipcount FROM rsh_user_vip";
		$query = $this->db->query($sql10);
		$ret10 = $query->row_array();
		$retData['vipcount'] = $ret10['vipcount'];
		
		//总计会员数
		$sql11 = "SELECT count(*) as ucount FROM rsh_user where type_id=2";
		$query = $this->db->query($sql11);
		$ret11 = $query->row_array();
		$retData['ucount'] = $ret11['ucount'];
		
		return $retData;
	}
	
	
	
	// 20150306 by  liub  查询还款标的信息，对应借款者
	function get_borrow_repay($data){
		$select = " bor.ftype,bor.id,bor.user_id,bor.user_id,bor.fstatus,bor.title,bor.account,bor.account_yes,bor.each_time,
			bor.is_day,bor.time_limit_day,bor.time_limit,bor.repayment_account,bor.repayment_yesaccount,bor.style,bor.bill_starttime,bor.bill_endtime";
		//封装条件
		$_where = " where 1=1 ";
		
		if (isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and bor.user_id = ".$data['where']['user_id'];
		}
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		//排序
		$_order  = " order by bor.id desc ";
		//封装sql
		$sql_result = "select $select from rsh_borrow as bor";
		$sql_result .= $_where;
		$sql_result .= $_order;
		if(isset($data['limit']) && $data['limit'] == 'all'){
			$query = $this->db->query($sql_result);
			$data['repay_list'] = $query->result_array();
			return $data;
		}else{
			$sql_result .= " limit $page_start, $page_size";
			$query = $this->db->query($sql_result);
			$data['repay_list'] = $query->result_array();
		}	
		
		//总记录条数
		$sql_count = "select count(1) as count from rsh_borrow as bor ";
		$sql_count .= $_where;
		$query = $this->db->query($sql_count);
		$data['repay_count'] = $query->row()->count;
		return $data;
	
	}
	
	// 20150306 by  liub  查询还款期数的信息，对应借款者
	function get_repay_list($data){
		//封装查询内容
		$select = "*";
		
		if($data['select'] == 1){
			$select = " t1.id, t1.fstatus, t1.forder, t1.borrow_id, t1.repayment_time,t1.repayment_yestime,
						t1.repayment_account, t1.repayment_yesaccount, t1.interest,t1.capital, t1.late_days, 
						t1.late_interest,t1.add_time,
						t2.id as borrow_id,t2.title, t2.account, t2.apr, t2.ftype, t2.time_limit, t2.is_day, 
						t2.time_limit_day,t2.style ";
		}
		$_where = " where 1=1";
		//封装条件
		if(isset($data['where']['user_id']) && $data['where']['user_id'] != ''){
			$_where .= " and t1.user_id = ".$data['where']['user_id'];
		}
		
		if(isset($data['where']['fstatus'])){
			$_where .= " and t1.fstatus = ".$data['where']['fstatus'];
		}
		
		if($data['type']==3){// 代还
			if (isset($data['where']['strtime']) && $data['where']['strtime']!=''){
				$strtime = strtotime($data['where']['strtime']);
				$_where .= " and t1.repayment_time >= ".$strtime;
			}
			if (isset($data['where']['endtime']) && $data['where']['endtime']!=''){
				$endtime = strtotime($data['where']['endtime'])+3600*24;
				$_where .= " and t1.repayment_time < ".$endtime;
			}
		
		}elseif($data['type']==4){//已还
			if (isset($data['where']['strtime']) && $data['where']['strtime']!=''){
				$strtime = strtotime($data['where']['strtime']);
				$_where .= " and t1.repayment_yestime >= ".$strtime;
			}
			if (isset($data['where']['endtime']) && $data['where']['endtime']!=''){
				$endtime = strtotime($data['where']['endtime'])+3600*24;
				$_where .= " and t1.repayment_yestime < ".$endtime;
			}
		}else{
			if (isset($data['where']['strtime']) && $data['where']['strtime']!=''){
				$strtime = strtotime($data['where']['strtime']);
				$_where .= " and t1.repayment_time >= ".$strtime;
			}
			if (isset($data['where']['endtime']) && $data['where']['endtime']!=''){
				$endtime = strtotime($data['where']['endtime'])+3600*24;
				$_where .= " and t1.repayment_time < ".$endtime;
			}
		}

		
		//排序
		$order  = " order by t1.id asc ";
		if(isset($data['order']) && $data['order'] == 1){
			$order  = " order by t1.repayment_time asc ";
		}elseif(isset($data['order']) && $data['order'] == 2){
			$order  = " order by t2.id asc ";
		}elseif(isset($data['order']) && $data['order'] == 3){
			$order  = " order by t1.id desc ";
		}elseif(isset($data['order']) && $data['order'] == 4){
			$order  = " order by t1.repayment_yestime desc ";
		}
		
		//封装sql
		$page_size = $data['page_size'];
		$page_start = $data['page_start'];
		$sql_result = "select $select from rsh_borrow_repayment as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id ";
		$sql_result .= $_where;
		$sql_result .= $order;
		
		//echo $sql_result;exit;
		if (isset($data['limit']) && $data['limit']=='all'){
			$query = $this->db->query($sql_result);
			return $query->result_array();
		}else{
			$sql_result .= " limit $page_start, $page_size";
			$query = $this->db->query($sql_result);
			if(isset($data['list']) && $data['list'] == 1){
				return $query->result_array();
			}
			$data['repayment_list'] = $query->result_array();
			
			//总记录条数
			$sql_count = "select count(*) as count from rsh_borrow_repayment as t1 left join rsh_borrow as t2 on t1.borrow_id=t2.id  ";
			$sql_count .= $_where;
			$query = $this->db->query($sql_count);
			$data['repayment_count'] = $query->row()->count;
			return $data;	
		}
		
	}
	
	function invite_user_account($wdata){
		$user_ids = implode(',',$wdata['invite_user']);
		$sql = " rsh_user usr LEFT JOIN rsh_borrow_tender tend  on tend.user_id = usr.user_id where  usr.invite_userid in (".$user_ids.") ";
		$where = "";
		$group = "";
		$order = "";
		$select = "*";
		if($wdata['user_details'] == '1') {
			$select = "usr.invite_userid 'inv_userid',usr.username 'username',usr.phone 'phone',from_unixtime(usr.add_time,'%Y%m%d') 'add_time',sum(tend.money) 'money',
			sum(IF(from_unixtime(tend.add_time,'%Y%m')='".$wdata['last_time']."',tend.money,0)) 'last_money',
			sum(IF(from_unixtime(tend.add_time,'%Y%m')='".$wdata['now_time']."',tend.money,0)) 'now_money' ";
			$group = " group by usr.user_id ";
			$order = "ORDER BY usr.invite_userid,usr.add_time ";
			$sql = "select ".$select." from ".$sql.$where.$group.$order;
			$sql_ = "select count(1) users from (".$sql.") as ter";
			if($wdata['page']) $sql .= " limit ".$wdata['page'].",".$wdata['page_size'] ;
			$query = $this->db->query($sql);
			$data['invite_user_account_list'] = $query->result_array();
			$query = $this->db->query($sql_);
			$res = $query->row_array();
			$data['total_rows'] = $res['users'];
		}
		else if($wdata['user_invite'] == '1') {
			$select = "usr.user_id,sum(tend.money) 'money',
			sum(IF(from_unixtime(tend.add_time,'%Y%m')='".$wdata['last_time']."',tend.money,0)) 'last_money',
			sum(IF(from_unixtime(tend.add_time,'%Y%m')='".$wdata['now_time']."',tend.money,0)) 'now_money' ";

			$m_time = date('m',time());
			$r = intval($m_time);
			for($i=0;$i<$r;$i++){
				$min_time = date('Ym',strtotime("-".$i." month"));
				$select .= ",sum(IF(from_unixtime(tend.add_time,'%Y%m')='".$min_time."',tend.money,0)) 'month".($r-$i)."_money' ";
				$select .= ",IF(from_unixtime(usr.add_time,'%Y%m')='".$min_time."',1,0) 'month".($r-$i)."_users' ";
			}
			
			$group = " group by usr.user_id ";
			
			$sql = "select ".$select." from ".$sql.$where.$group.$order;
			//echo $sql.'<br>';
			$query = $this->db->query($sql);
		 	$ret = $query->result_array();
		 	$i=0;
		 	$rer = array();
			$dae = array('money'=>0,'money_ti'=>0,'last_money'=>0,'last_money_ti'=>0,'now_money'=>0,'now_money_ti'=>0,
						'month1_money'=>0,'month1_users'=>0,'month2_money'=>0,'month2_users'=>0,'month3_money'=>0,'month3_users'=>0,
						'month4_money'=>0,'month4_users'=>0,'month5_money'=>0,'month5_users'=>0,'month6_money'=>0,'month6_users'=>0,
						'month7_money'=>0,'month7_users'=>0,'month8_money'=>0,'month8_users'=>0,'month9_money'=>0,'month9_users'=>0,
						'month10_money'=>0,'month10_users'=>0,'month11_money'=>0,'month11_users'=>0,'month12_money'=>0,'month12_users'=>0);
			foreach($ret as $v){
				$rer[$i] = $v['user_id'];
				$dae['money'] += $v['money'];
				$dae['last_money'] += $v['last_money'];
				$dae['now_money'] += $v['now_money'];
				for($j=1;$j<=$r;$j++){
					$dae['month'.$j.'_money'] += $v['month'.$j.'_money'];
					$dae['month'.$j.'_users'] += $v['month'.$j.'_users'];
				}
				$i++;
			}
			$dae['count_userid'] = $i;
			$data['users_id'] = $rer;
			$data['invite_user_account_list'] = $dae;
		}
		return $data;
	}
	
	function dataanalysis($rdata){
		$sql = "";
		$where = "";
		$group = "";
		$order = "";
		$select = "*";
		$_select1 = "";
		$_select2 = "";
		$type = $rdata['types'];
		$kk = 1000;   //金额以此数为单位
		
		if($rdata['type'] == 'perhour'){
			$min = isset($rdata['min'])?$rdata['min']:6;
			$max = isset($rdata['max'])?$rdata['max']:23;
			$cha = $max - $min +1;
			$nowtime = date("Ymd");
			if($cha>0) $select = "";
			for($i=0;$i<$cha;$i++){
				$time = $nowtime.($min+$i);
				$select .= " sum(IF(from_unixtime(usr.lasttime,'%Y%m%d%k')='".$time."' || from_unixtime(usr.uptime,'%Y%m%d%k')='".$time."',1,0)) ".$type[1]."_hour".$i;
				
				$_select0 .= "sum(IF(from_unixtime(tend.add_time,'%Y%m%d%k')='".$time."',1,0)) ".$type[6]."_hour".$i;
				$_select0 .= ",sum(IF(from_unixtime(tend.add_time,'%Y%m%d%k')='".$time."',tend.money,0)) ".$type[7]."_hour".$i;
				
				$_select1 .= "sum(IF(from_unixtime(rech.add_time,'%Y%m%d%k')='".$time."',1,0)) ".$type[2]."_hour".$i;
				$_select1 .= ",sum(IF(from_unixtime(rech.add_time,'%Y%m%d%k')='".$time."',rech.money,0)) ".$type[4]."_hour".$i;
				
				$_select2 .= "sum(IF(from_unixtime(cash.add_time,'%Y%m%d%k')='".$time."',1,0)) ".$type[3]."_hour".$i;
				$_select2 .= ",sum(IF(from_unixtime(cash.add_time,'%Y%m%d%k')='".$time."',cash.total,0)) ".$type[5]."_hour".$i;
				
				if($i<($cha-1)) {
					$select.= ",";
					$_select0.= ",";
					$_select1.= ",";
					$_select2.= ",";
				}
			}
			$sql = " rsh_user usr where from_unixtime(usr.lasttime,'%Y%m%d')=".$nowtime;
			$sql = "select ".$select." from ".$sql;
			$query = $this->db->query($sql);
		 	$ret = $query->result_array();
		 	
		 	$sql = " rsh_borrow_tender tend where from_unixtime(tend.add_time,'%Y%m%d')=".$nowtime;
		 	$sql = "select ".$_select0." from ".$sql;
			$query = $this->db->query($sql);
		 	$_ret0 = $query->result_array();
		 	
		 	$sql = " rsh_account_recharge rech where rech.fstatus=1 ";
		 	$sql = "select ".$_select1." from ".$sql;
		 	$query = $this->db->query($sql);
		 	$_ret1 = $query->result_array();
		 	
		 	$sql = " rsh_account_cash cash where cash.fstatus!=3 ";
		 	$sql = "select ".$_select2." from ".$sql;
		 	$query = $this->db->query($sql);
		 	$_ret2 = $query->result_array();
		 	
		 	for($i=0;$i<$cha;$i++){
		 		$data[$type[1]][$i] = isset($ret[0][$type[1].'_hour'.$i])?$ret[0][$type[1].'_hour'.$i]:0;
		 		$data[$type[2]][$i] = isset($_ret1[0][$type[2].'_hour'.$i])?$_ret1[0][$type[2].'_hour'.$i]:0;
		 		$data[$type[3]][$i] = isset($_ret2[0][$type[3].'_hour'.$i])?$_ret2[0][$type[3].'_hour'.$i]:0;
		 		$data[$type[4]][$i] = isset($_ret1[0][$type[4].'_hour'.$i])?round($_ret1[0][$type[4].'_hour'.$i]/$kk, 2):0;
		 		$data[$type[5]][$i] = isset($_ret2[0][$type[5].'_hour'.$i])?round($_ret2[0][$type[5].'_hour'.$i]/$kk, 2):0;
		 		$data[$type[6]][$i] = isset($_ret0[0][$type[6].'_hour'.$i])?$_ret0[0][$type[6].'_hour'.$i]:0;
		 		$data[$type[7]][$i] = isset($_ret0[0][$type[7].'_hour'.$i])?round($_ret0[0][$type[7].'_hour'.$i]/$kk, 2):0;
		 	}
		}
		else {
			if($rdata['type'] == 'everyday'){
				$scale = $rdata['scale'];	//尺度
				$nowtime = date("Ymd");
				if($scale>0) $select = "";
				for($i=0;$i<$scale;$i++){
					$time = date('Ymd',strtotime("-".$i." day"));
					$select .= " sum(IF(from_unixtime(usr.add_time,'%Y%m%d')='".$time."',1,0)) ".$type[1]."_".$rdata['type'].$i;
					
					$_select0 .= "sum(IF(from_unixtime(tend.add_time,'%Y%m%d')='".$time."',1,0)) ".$type[3]."_".$rdata['type'].$i;
					$_select0 .= ",sum(IF(from_unixtime(tend.add_time,'%Y%m%d')='".$time."',tend.money,0)) ".$type[6]."_".$rdata['type'].$i;
					$_select0 .= ",sum(IF(from_unixtime(tend.add_time,'%Y%m%d')='".$time."',tend.money-tend.account,0)) ".$type[8]."_".$rdata['type'].$i;
					
					$_select1 .= "sum(IF(from_unixtime(rech.add_time,'%Y%m%d')='".$time."',1,0)) ".$type[2]."_".$rdata['type'].$i;
					$_select1 .= ",sum(IF(from_unixtime(rech.add_time,'%Y%m%d')='".$time."',rech.money,0)) ".$type[5]."_".$rdata['type'].$i;
					
					$_select2 .= "sum(IF(from_unixtime(cash.add_time,'%Y%m%d')='".$time."',1,0)) ".$type[4]."_".$rdata['type'].$i;
					$_select2 .= ",sum(IF(from_unixtime(cash.add_time,'%Y%m%d')='".$time."',cash.total,0)) ".$type[7]."_".$rdata['type'].$i;
					
					if($i<($scale-1)) {
						$select.= ",";
						$_select0.= ",";
						$_select1.= ",";
						$_select2.= ",";
					}
				}

			}
			elseif($rdata['type'] == 'weekly'){
				$scale = $rdata['scale'];	//尺度
				$nowtime = date("Ymd");
				if($scale>0) $select = "";
				$nowyear = intval(date("Y"));
				$weeknum = date('W');
				for($i=0;$i<$scale;$i++){
					if($weeknum < 1) {
						$nowyear = $nowyear-1;
						$weeknum = $this->getweeknum($nowyear);
						$date_scale = $this->getWeekDate($nowyear,$weeknum);
						if($date_scale[0] == $start) $weeknum--;
					}
					$date_scale = $this->getWeekDate($nowyear,$weeknum);
					$start = $date_scale[0];
					$end = $date_scale[1];
					$time = date('Ymd',strtotime("-".$i." day"));
					$select .= " sum(IF(from_unixtime(usr.add_time,'%Y%m%d')>='".$start."' && from_unixtime(usr.add_time,'%Y%m%d')<='".$end."',1,0)) ".$type[1]."_".$rdata['type'].$i;
					
					$_select0 .= "sum(IF(from_unixtime(tend.add_time,'%Y%m%d')>='".$start."' && from_unixtime(tend.add_time,'%Y%m%d')<='".$end."',1,0)) ".$type[3]."_".$rdata['type'].$i;
					$_select0 .= ",sum(IF(from_unixtime(tend.add_time,'%Y%m%d')>='".$start."' && from_unixtime(tend.add_time,'%Y%m%d')<='".$end."',tend.money,0)) ".$type[6]."_".$rdata['type'].$i;
					$_select0 .= ",sum(IF(from_unixtime(tend.add_time,'%Y%m%d')>='".$start."' && from_unixtime(tend.add_time,'%Y%m%d')<='".$end."',tend.money-tend.account,0)) ".$type[8]."_".$rdata['type'].$i;
					
					$_select1 .= "sum(IF(from_unixtime(rech.add_time,'%Y%m%d')>='".$start."' && from_unixtime(rech.add_time,'%Y%m%d')<='".$end."',1,0)) ".$type[2]."_".$rdata['type'].$i;
					$_select1 .= ",sum(IF(from_unixtime(rech.add_time,'%Y%m%d')>='".$start."' && from_unixtime(rech.add_time,'%Y%m%d')<='".$end."',rech.money,0)) ".$type[5]."_".$rdata['type'].$i;
					
					$_select2 .= "sum(IF(from_unixtime(cash.add_time,'%Y%m%d')>='".$start."' && from_unixtime(cash.add_time,'%Y%m%d')<='".$end."',1,0)) ".$type[4]."_".$rdata['type'].$i;
					$_select2 .= ",sum(IF(from_unixtime(cash.add_time,'%Y%m%d')>='".$start."' && from_unixtime(cash.add_time,'%Y%m%d')<='".$end."',cash.total,0)) ".$type[7]."_".$rdata['type'].$i;
					
					if($i<($scale-1)) {
						$select.= ",";
						$_select0.= ",";
						$_select1.= ",";
						$_select2.= ",";
					}
					$weeknum = $weeknum-1;
				}
			 	$nowyear = intval(date("Y"));
			 	$weeknum = date('W');
				
			}
			elseif($rdata['type'] == 'monthly'){
				$scale = $rdata['scale'];	//尺度
				if($scale>0) $select = "";
				for($i=0;$i<$scale;$i++){
					$time = date('Ym',strtotime("-".$i." month"));
					$select .= " sum(IF(from_unixtime(usr.add_time,'%Y%m')='".$time."',1,0)) ".$type[1]."_".$rdata['type'].$i;
					
					$_select0 .= "sum(IF(from_unixtime(tend.add_time,'%Y%m')='".$time."',1,0)) ".$type[3]."_".$rdata['type'].$i;
					$_select0 .= ",sum(IF(from_unixtime(tend.add_time,'%Y%m')='".$time."',tend.money,0)) ".$type[6]."_".$rdata['type'].$i;
					$_select0 .= ",sum(IF(from_unixtime(tend.add_time,'%Y%m')='".$time."',tend.money-tend.account,0)) ".$type[8]."_".$rdata['type'].$i;
					
					$_select1 .= "sum(IF(from_unixtime(rech.add_time,'%Y%m')='".$time."',1,0)) ".$type[2]."_".$rdata['type'].$i;
					$_select1 .= ",sum(IF(from_unixtime(rech.add_time,'%Y%m')='".$time."',rech.money,0)) ".$type[5]."_".$rdata['type'].$i;
					
					$_select2 .= "sum(IF(from_unixtime(cash.add_time,'%Y%m')='".$time."',1,0)) ".$type[4]."_".$rdata['type'].$i;
					$_select2 .= ",sum(IF(from_unixtime(cash.add_time,'%Y%m')='".$time."',cash.total,0)) ".$type[7]."_".$rdata['type'].$i;
					
					if($i<($scale-1)) {
						$select.= ",";
						$_select0.= ",";
						$_select1.= ",";
						$_select2.= ",";
					}
				}
			}
			
			
			$sql = " rsh_user usr ";
			$sql = "select ".$select." from ".$sql;
			$query = $this->db->query($sql);
		 	$ret = $query->result_array();
		 	
		 	$sql = " rsh_borrow_tender tend ";
		 	$sql = "select ".$_select0." from ".$sql;
			$query = $this->db->query($sql);
		 	$_ret0 = $query->result_array();
		 	
		 	$sql = " rsh_account_recharge rech where rech.fstatus=1 ";
		 	$sql = "select ".$_select1." from ".$sql;
		 	$query = $this->db->query($sql);
		 	$_ret1 = $query->result_array();
		 	
		 	$sql = " rsh_account_cash cash where cash.fstatus!=3 ";
		 	$sql = "select ".$_select2." from ".$sql;
		 	$query = $this->db->query($sql);
		 	$_ret2 = $query->result_array();
			for($i=0;$i<$scale;$i++){
				if($rdata['type'] == 'everyday'){
					$time = date('md',strtotime("-".$i." day"));
					$data['dayname'.$i] =  $time;
				}
				elseif($rdata['type'] == 'weekly'){
					if($weeknum < 1) {
						$nowyear = $nowyear-1;
						$weeknum = $this->getweeknum($nowyear);
						$date_scale = $this->getWeekDate($nowyear,$weeknum);
						if($date_scale[0] == $start) $weeknum--;
					}
					$date_scale = $this->getWeekDate($nowyear,$weeknum);
					$start = $date_scale[0];
					$data['dayname'.$i] =  $nowyear."年".$weeknum.'周';
					$weeknum = $weeknum-1;
				}
				elseif($rdata['type'] == 'monthly'){
					$time = date('Y-m',strtotime("-".$i." month"));
					$data['dayname'.$i] = $time;
				}
			
		 		$data[$type[1]][$i] = isset($ret[0][$type[1].'_'.$rdata['type'].$i])?$ret[0][$type[1].'_'.$rdata['type'].$i]:0;
		 		$data[$type[2]][$i] = isset($_ret1[0][$type[2].'_'.$rdata['type'].$i])?$_ret1[0][$type[2].'_'.$rdata['type'].$i]:0;
		 		$data[$type[3]][$i] = isset($_ret0[0][$type[3].'_'.$rdata['type'].$i])?$_ret0[0][$type[3].'_'.$rdata['type'].$i]:0;
		 		$data[$type[4]][$i] = isset($_ret2[0][$type[4].'_'.$rdata['type'].$i])?$_ret2[0][$type[4].'_'.$rdata['type'].$i]:0;
		 		$data[$type[5]][$i] = isset($_ret1[0][$type[5].'_'.$rdata['type'].$i])?round($_ret1[0][$type[5].'_'.$rdata['type'].$i]/$kk, 2):0;
		 		$data[$type[6]][$i] = isset($_ret0[0][$type[6].'_'.$rdata['type'].$i])?round($_ret0[0][$type[6].'_'.$rdata['type'].$i]/$kk, 2):0;
		 		$data[$type[7]][$i] = isset($_ret2[0][$type[7].'_'.$rdata['type'].$i])?round($_ret2[0][$type[7].'_'.$rdata['type'].$i]/$kk, 2):0;
		 		$data[$type[8]][$i] = isset($_ret0[0][$type[8].'_'.$rdata['type'].$i])?round($_ret0[0][$type[8].'_'.$rdata['type'].$i]/$kk, 2):0;
		 	}

		}
		return $data;
	}
	
	private  function get_week($year) {
	    $num = $this->getweeknum($year);
	    for ($i = 1; $i <= $num; $i++) { 
	        $week_array[$i] = $this->getWeekDate($year,$i);
	    } 
	    return $week_array; 
	} 
	private function getweeknum($year){
		$weeknum= floor(((mktime (0,0,0,12,31,$year) - mktime(0,0,0,1,1,$year)))/(3600*24*7))+1;
		$num = intval($weeknum);
		return $num;
	}
 	private function getWeekDate($year,$weeknum){ 
		$format = "Ymd"; 
	    $firstdayofyear=mktime(0,0,0,1,1,$year);  
	    $firstweekday=date('N',$firstdayofyear);  
	    $firstweenum=date('W',$firstdayofyear);  
	    if($firstweenum==1){  
	        $day=(1-($firstweekday-1))+7*($weeknum-1);  
	        $startdate=date($format,mktime(0,0,0,1,$day,$year));  
	        $enddate=date($format,mktime(0,0,0,1,$day+6,$year));  
	    }else{  
	        $day=(9-$firstweekday)+7*($weeknum-1);  
	        $startdate=date($format,mktime(0,0,0,1,$day,$year));  
	        $enddate=date($format,mktime(0,0,0,1,$day+6,$year));  
	    }
	    return array($startdate,$enddate);
	}
}
